我有以下代码片段:
def isolation_level(level):
def decorator(fn):
def recur(level, *args, **kwargs):
if connection.inside_block:
if connection.isolation_level < level:
raise IsolationLevelError(connection)
else:
fn(*args, **kwargs)
else:
connection.enter_block()
try:
connection.set_isolation_level(level)
fn(*args, **kwargs)
connection.commit()
except IsolationLevelError, e:
connection.rollback()
recur(e.level, *args, **kwargs)
finally:
connection.leave_block()
def newfn(*args, **kwargs):
if level is None: # <<<< ERROR MESSAGE HERE, Unbound local variable `level`
if len(args):
if hasattr(args[0], 'isolation_level'):
level = args[0].isolation_level
elif kwargs.has_key('self'):
if hasattr(kwargs['self'], 'isolation_level'):
level = kwargs.pop('self', 1)
if connection.is_dirty():
connection.commit()
recur(level, *args, **kwargs)
return newfn
return decorator
这真的不重要,但我张贴它的原始形式,因为我无法重现任何更简单的情况。
问题是,当我调用isolation_level(1)(some_func)(some, args, here)
时,我在第21行(在清单上标记)中得到Unbound local variable
异常。我不明白为什么。我尝试重新创建相同的函数和函数调用结构,但不包含所有实现细节,以找出问题所在。然而,我没有得到异常消息。例如:
def outer(x=None):
def outer2(y):
def inner(x, *args, **kwargs):
print x
print y
print args
print kwargs
def inner2(*args, **kwargs):
if x is None:
print "I'm confused"
inner(x, *args, **kwargs)
return inner2
return outer2
outer(1)(2)(3, z=4)
打印:
1
2
(3,)
{'z': 4}
我错过了什么??
编辑
好的,问题是,在第一个版本中,我实际上对变量执行了赋值。Python检测到这一点,因此假设该变量是本地的。
局部变量是在编译时确定的:对发生错误的行下面几行变量level
的赋值使该变量成为内部函数的局部变量。所以这行
if level is None:
实际上试图访问最内层作用域中的变量level
,但是这样的变量还不存在。在Python 3中。您可以通过声明
nonlocal level
如果您确实想要更改外部函数的变量,则在内部函数的开头使用。否则,您可以在内部函数中使用不同的变量名。