I noticed this behavior in Python 2 and 3:
>>> id(lambda: 1) == id(lambda: 2)
True
They share the same hash as well.
>>> hash(lambda: 1) == hash(lambda: 2)
True
I expected to have two different ids and hashes for the two lambda functions.
I investigated more, and I found a similar behavior when returning closures:
>>> def foo(n):
... def bar():
... return n
... return bar
...
>>> id(foo(1)) == id(foo(2))
True
In this case, I suppose the id is the same because the function returned is exactly the same, and what is changing is just the enclosing scope.
Is anything similar happening with lambda functions?
This has nothing to do with scope, or lambdas, or closures. It is simply that Python manages memory with reference counting, and those lambdas are never assigned to any references, so Python immediately deletes them and reuses the memory location for the next object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With