[Tutor] New Python scoping

dman dsh8290@rit.edu
Tue, 6 Nov 2001 16:37:15 -0500


On Tue, Nov 06, 2001 at 12:25:41AM -0800, Tommy Butler wrote:
| 
|    From: alan.gauld@bt.com
|    To: python.tutor@atrixnet.com, tutor@python.org
|    Subject: RE: [Tutor] New Python scoping
|    Date: Mon, 5 Nov 2001 11:03:42 -0000
| 
|    >>Can someone explain Python scoping rules in general
|    >>for me, taking into account these new changes?
| 
|    >I'll leave that to somebody else :-)
| 
| Any takers?

If you are using version 2.1, put the line

    from __future__ import nested_scopes

as the first non-blank, non-comment, and non-docstring line in the
file.

If you are using 2.2 or newer, this is not needed (you have no choice
but to use nested scopes).

Then to test it out use the following code


a = 1
def f() :
    a = 2
    def g()
        print a
    g()
f()


If the language has statically nested scopes, then you will get '2'
printed out.  If you remove the "future statement" (as that line above
is called) from the file you will get "1" printed out.


Have you programmed in C, C++ or Java at all?  If so, then Python's
scoping is the same except that you can define a function inside
another, and instances of inner classes don't automagically have
unqualified access to outer-class members (a java hack to work around
the lack of references to functions).

HTH,
-D