question about scope

Fredrik Lundh fredrik at pythonware.com
Fri Feb 17 04:56:21 EST 2006


John Salerno wrote:

> > I understand what global and built-in are, and I thought I understood
> > the concept of local too, but when I got to this sentence (and the
> > previous sentence), I became confused about the first two scopes. What's
> > the difference between 'local' and 'enclosing functions'?
>
> I guess maybe I jumped the gun. Here's some stuff later in the chapter
> that I think explains it for me:
>
> ----------
> Note that the second 'E' scope lookup layer -- enclosing defs or lambdas
> -- technically can correspond to more than one lookup layer. It only
> comes into play when you nest functions within functions.*
>
> * The scope lookup rule was known as the "LGB" rule in the first edition
> of this book. The enclosing def layer was added later in Python, to
> obviate the task of passing in enclosing scope names explicitly -- 
> something usually of marginal interest to Python beginners.
> ----------

that footnote is slightly misleading, though -- there's no way to pass
in enclosing scope names in Python.  what you can do is to pass in
*objects* into an inner scope, using the default argument syntax.  an
example:

    var = "global"

    def func1(arg):
        print var

    def func2(arg, var=var):
        print var

here, func1's "var" is bound to the *name* of the outer variable, so if
the variable is changed, it will print the new value.

in contrast, func2's "var" is bound to the *value* that the outer variable
had when the def statement was executed, so it will print the same thing
every time you call it, even if the outer variable is changed.

what the note refers to in modern python, the name binding (in func1)
also works as expected if you nest scope:

    var = 0 # global

    def outer():

        var = 1 # local to outer, enclosing in func1

        def func1(arg):
            print var #enclosing in today's python, global in old pythons

        def func2(arg, var=var):
            print var

        func1() # prints 1 in today's python, 0 in old pythons
        func2() # prints 1 in all versions

        var = 2

        func1() # prints 2 in today's python, 0 in old pythons
        func2() # prints 1

(I hope this didn't confuse things even more.)

</F>






More information about the Python-list mailing list