Closures in python

Python lets you package a function as a variable. This means you can return it from a function.

result ...

So the inner function grabs the x value at definition, it then remembers this value.

this effect is known as a closure.

essentially the outer function works as a factory, creating the inner at run time, locking in the value for x.

ok now lets think about how variables are scoped...

Look at the cunning use of the global keyword which points the inner definition to the global scope


results in this...


So the global keyword lets you change a globally defined variable, that is a variable defined at the highest level.

to modify the variable within the enclosing function, we need the keyword nonlocal


results in this...


This is all very good and interesting, lets use it for something practical....

a timer function


as you can see this is pretty awesome, but its not something you will probably use often, you can also see how browser timing is not very exact.






comments powered by Disqus