0

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?

luisfernando
  • 117
  • 1
  • 4
  • 1
    @AshwiniChaudhary: nice find; I forgot I answered this before. :-) – Martijn Pieters Feb 10 '14 at 10:56
  • Thank you guys, but now I am a bit more confused. I am trying to generate OrderedDict nested structures to generate xmls with xmltodict. So I call the children element from the children elements to append them to the parent element. When I call the method multiple times I get extra elements. Although apparently the variable is not stored inside the object. – luisfernando Feb 10 '14 at 11:03
  • 1
    @user3292520: that's an entirely *different* issue. You could make that a new question, but do include a good small sample to reproduce the behaviour you see. – Martijn Pieters Feb 10 '14 at 11:07
  • I am going to do that, thanks for your kind help. – luisfernando Feb 10 '14 at 11:33

2 Answers2

4

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

This is what the id() function does, it returns a unique identifier of an object, you are creating several objects, so you get different ids.

tk.
  • 626
  • 4
  • 14