0

I've noticed some strange behavior with calling str(lambda: foo) in python. If I assign a lambda to two different variables, it will go to two different memory locations, even if the lambda is clearly the same. For example:

>>> a = lambda: 1
>>> b = lambda: 1
>>> str(a)
'<function <lambda> at 0x0000000000AC6730>'
>>> str(b)
'<function <lambda> at 0x0000000000AC66A8>'

OK, so when I create and assign two lambdas, they occupy different memory locations. So far so good. However, if I create a bunch of lambdas and do not assign them, they are always go to the same place, no matter how radically different the lambdas are. For example, if I run this:

>>> print(str(lambda: 1))
<function <lambda> at 0x00000000011B6730>
>>> print(str(lambda: "Hello"))
<function <lambda> at 0x00000000011B6730>
>>> print(str(lambda: str))
<function <lambda> at 0x00000000011B6730>
>>> print(str(lambda: (lambda: (lambda: 1))))
<function <lambda> at 0x00000000011B6730>

As far as I can tell, this behavior is the same regardless of whether I use python 2 or 3. What's causing this strange behavior?

DJMcMayhem
  • 7,285
  • 4
  • 41
  • 61
  • 2
    The function object gets garbage collected and then the memory location is reused. It's an implementation detail. You should not care about the memory location of of an object. – Steven Rumbalski Dec 12 '16 at 17:42
  • I have no idea but I imagine it might get gc-ed when it's not stored so what you see is that you create them at the same available space. If you were to store it the address will be different. – Sylwester Dec 12 '16 at 17:45

1 Answers1

1

so when I create and assign two lambdas, they occupy different memory locations

When you invoke str(lambda: 1), it creates a lambda object, then converts that to a string, and finally throws away that lambda object. Hence, when you create another lambda object it happens to occupy the same space because freed memory gets reused.

This is likely to happen with CPython, but less so with Python implementations based on virtual machines with delayed garbage collection.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271