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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -