Nested scopes question

Mark McEahern marklists at mceahern.com
Fri Jul 19 00:02:03 EDT 2002


> In the following code:
>
> def foo():
>     def bar():
>         print 'x from foo',x
>         x+=1
>
>     x=0
>     for i in range(5):
>         bar()
>
> foo()

This seems to me a clearer statement of what I think you're trying to do:

def make_bar(x):
    def bar():
        print x
        x += 1
    return bar

def foo():
    x = 0
    bar = make_bar(x)
    for i in range(5):
        bar()

foo()

**

This is the result:

$ python junk.py
Traceback (most recent call last):
  File "junk.py", line 13, in ?
    foo()
  File "junk.py", line 11, in foo
    bar()
  File "junk.py", line 3, in bar
    print x
UnboundLocalError: local variable 'x' referenced before assignment

You might want to read this thread:

  http://groups.google.com/groups?selm=3B98F3B0.53AC2524%40swiftview.com

As Frederik Lundh points out:


http://groups.google.com/groups?selm=Eo7m7.53652%24e5.2684084%40newsb.telia.
net

once you bind x in bar(), it is considered local.  End of story.

If I remember correctly, this is the example Paul Graham used to make fun of
Python as not yet quite having evolved into Lisp.  ;-)

// mark

-






More information about the Python-list mailing list