Search code examples
pythonpython-collections

Why OrderedDict has this behavior


In Python 2.7 I am having this behavior with OrderedDict

from collections import *
id(OrderedDict())
42101904
id(OrderedDict())
42071680
id(OrderedDict())
42071680
id(OrderedDict())
42071680
id(OrderedDict())
42071680

Why?


Solution

  • That's not specific to OrderedDict(), Python is reusing freed memory to store the new object.

    From the id() function documentation:

    Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

    You are creating a OrderedDict() object only for the id() call, and when that call completes there is nothing else referencing the object anymore. It is thus removed from memory again, and the next time you run id(OrderedDict()) a new object is created at the exact same memory location.