function - Unbound local variable problem in Python -
i've got following code snippet:
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 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
it doesn't matter does, post in original form, unable recreate situation simpler.
the problem when call isolation_level(1)(some_func)(some, args, here)
unbound local variable
exception in line 21 (marked on listing). don't understand why. tried recreating same structure of functions , function calls wouldn't contain implementation details figure out wrong. don't exception message then. example following works:
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 none: print "i'm confused" inner(x, *args, **kwargs) return inner2 return outer2 outer(1)(2)(3, z=4)
prints:
1 2 (3,) {'z': 4}
what missing??
edit
ok, problem in first version perform assignment variable. python detects , therefore assumes variable local.
local variables determined @ compile time: assignments variable level
few lines below line error occurs in make variable local inner function. line
if level none:
actually tries access variable level
in innermost scope, such variable not exist yet. in python 3.x, can solve problem declaring
nonlocal level
at beginning of inner function, if want alter variable of outer function. otherwise, can use different variable name in inner function.
Comments
Post a Comment