gpt4 book ai didi

python - Python 3.4 中的 UnboundLocalError

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:51 24 4
gpt4 key购买 nike

<分区>

以下代码在 Python 2.7 中有效,但在 Python 3.4 中引发此异常:

  File "/home/sean/dev/ving/meridian/venv/src/django-testmigrate/django_testmigrate/base.py", line 70, in __getattr__
if e:
UnboundLocalError: local variable 'e' referenced before assignment

e 被赋值在同一个函数的顶部。我假设 Python 3 中有一些新的范围规则,但我找不到对它们的任何引用。

代码如下:

def __getattr__(self, name):
e = None

if not self._store:
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))

for state, scope in reversed(list(self._store.items())):
try:
val = getattr(scope, name)
except AttributeError as e:
continue
else:
e = None

# get fresh instance
if state != self._current_state and isinstance(val, models.Model):
model_meta = val.__class__._meta
model_class = self._current_state.get_model(model_meta.app_label, model_meta.model_name)
val = model_class.objects.get(pk=val.pk)

# add this value to the current scope
setattr(self, name, val)
break

if e: # error raised here
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))

return val

更新:

我通过如下修改我的代码让它工作:

except AttributeError as ex:
# needed for Python 3 compatibility
e = ex
continue

不知何故 except...as 实际上是从局部作用域中删除了变量 e。对我来说,这似乎是 Python 中的一个错误。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com