views:

158

answers:

1

Hi,

I'm a beginning python programmer, and I'd like someone to clarify the following behavior.

I have the following code:

env = lambda id: -1

def add(id, val, myenv):
    return lambda x: val if x == id else myenv(id)

test_env = add("a", 1, env)
test_env_2 = add("b", 2, test_env)

When I look up "a" in test_env, it functions correctly, but when I look it up in test_env_2 it seems to have been clobbered by "b". At least, "b" is all I can retrieve from test_env_2.

So, I have already read http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters et al and understand that closures operate on references rather than values, but I believe this is not the exact same case since I am using string literals. Can someone explain to me what is going on under the hood here?

(And yes, I know that Python isn't intended as a functional language. This is just research.)

+5  A: 

I think you just confused myenv(id) with myenv(x). Change it and you'll get the desired output.

Dario
What a stupid error. Thanks.
danben