Is there "let binding" in Python?

Hans Nowak hans at zephyrfalcon.org
Tue Sep 16 16:06:34 EDT 2003


Rob Hunter wrote:

Hi,

>>It's not mutation, it's assignment.
>>
> 
> 
> I had always used the word mutation basically for
> any use of a "!" in Scheme, but fair enough.

Well... there may be a difference in terminology... but IIRC, set! and friends 
are used for a variable that already exists.  In Python, 'x = 1' is always an 
assignment (or a binding of a name, whatever you want to call it).  If x 
already exists, you could call it mutation I guess, but it doesn't matter 
whether x already existed in the namespace, or not.

> 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'm not sure it has much to do with assignment.

> I believe you when you say this is how Python
> does it, but I'd like to know what's wrong with
> the model I have.  Can you give me an example
> where my model fails me?  To review, I am saying,
> now just for the sake of argument and
> understanding Python, that the first "=" is
> special and acts like a Scheme LET while
> subsequent "=" with the same variable name in
> scope act like assignments.

No, a statement like 'x = 1' does the same whether x already exists or not: it 
creates an integer object with value 1 (or reuses a cached one, but never mind 
that right now), and binds it to the name 'x' in the current namespace.

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list