Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory address of a lambda function

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?

like image 310
vrde Avatar asked Mar 23 '26 23:03

vrde


1 Answers

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.

like image 131
Daniel Roseman Avatar answered Mar 25 '26 13:03

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!