Nested Lambdas in Python

I am starting a python programmer and I would 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 at "a" in test_env, it functions correctly, but when I look at it in test_env_2, it seems to be clogged with the letter "b". At least “b” is all I can get from test_env_2.

So, I already read the scope of python lambda functions and their parameters , etc., and understand that closures work on links, not values, but I believe that this is not the same case, since I use string literals. Can someone explain to me what is happening here under the hood?

(And yes, I know that Python is not intended as a functional language. It is just a study.)

+3
1

, myenv(id) myenv(x). , .

+5

Source: https://habr.com/ru/post/1723708/


All Articles