3

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 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.)

1
  • 1
    Python is multiparadigm, but functional style is considered pythonically! Commented Nov 23, 2009 at 20:48

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.