Python closures: function defined inside of function can access variables one level above? -
i'm learning decorators, , have question. in decorator function call_counter
, function defined , returned, , "replace" function func
passed in parameter decorator function.
def call_counter(func): def helper(*args, **kwargs): helper.calls += 1 return func(*args, **kwargs) helper.calls = 0 return helper
once done, can access helper.calls
outside function in manner:
@call_counter def addition(x, y): return x + y print(addition.calls) addition(1, 2) print(addition.calls)
the output:
0 1
my question is, how can helper.calls
variable exist in memory after call_counter
function has been called , exited? far understand, helper.calls
exists in call_counter
's memory. seems unlikely if variable can accessed after execution of call_counter
finished.
calls
property of helper
, live until helper
dies, , helper
not going die because, said, live under addition
name.
Comments
Post a Comment