Nested Scopes

In Python 2.1, nested functions defined nested scopes

  • Optional feature that must be enabled using:
     from __future__ import nested_scopes

Example

 def foo():
     x = 1
     def bar():
         print x    # Use of nonlocal variable
     while x < 10:
         bar()
         x += 1

In previous versions of Python

  • This code generates a NameError exception (x not defined).
  • No notion of an "enclosing" scope (only local and global scope).

In Python 2.1: It works!

<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 18
July 26, 2001, beazley@cs.uchicago.edu
>>>