Tuesday, September 16, 2014

Python: Nested Scopes

Python 2.2 introduced the concept of Nested Scopes(Details) that affects the namespace search order. Prior to Python 2.2, when you reference a variable within a nested functionPython will search for that variable in the current function's namespace, then in the module's namespace. 

Python 2.2 will search for the variable in the current function's namespace, then in the parent function's namespace, then in the module's namespace. 

Python 2.1 can work either way; by default, it works like Python 2.0, but you can add the following line of code at the top of your module to make your module work like Python 2.2:

from __future__ import nested_scopes