Is there "let binding" in Python?

Rob Hunter rhunter007 at yahoo.com
Tue Sep 16 16:24:30 EDT 2003


> 
> > Well, yeah.  And that's a good thing, right? 
> I
> > mean, perhaps not in general, but certainly
> in
> > this case I think everyone can agree that it
> is
> > *assignment* which creates the confusing
> issue of
> > all buttons being named 10.
> 
> Depends on how you look at it:
> 
> [Jeff's example code]
> def make_stupid_gui():
>      t = Tk()
>      for i in range(10):
>          b = Button(t, text="Button #%d" % i,
>              command=lambda: button_func(i))
>          b.pack()
> make_stupid_gui()
> 
> The reason that you get surprising results, is
> that the i in 
> button_func(i) isn't evaluated until that piece
> of code is actually 
> called.  When it's called, it looks at the
> value that i has *at that 
> moment*.  The value it had when the button and
> the lambda were created, 
> is not stored anywhere, so it cannot be used. 


I don't *think* that's correct (though I could be
wrong).  What you're describing is "dynamic
scoping".  That's where the body of a function
(or code block in this case) isn't evaluated
until it is used.  And thus, free variables in
the body assume whatever values their calling
environment has.  Dynamic scoping is a bad thing.
 So bad, in fact, that lisp added (at least the
option of, I think) static scoping, Scheme
exclusively uses static scoping, and that Python
corrected their mistake (it used to be
dynamically scoped).

But anyway, from my tests, and from what I've
read, Python has static scoping, but what
assignment allows you to do is violate, in a way,
this static scoping, which is what we see here.

Rob

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com





More information about the Python-list mailing list