1

I really confuse that a behavior of id() function on IronPython who differ from Python. Let me show you the following code,

In IronPython:

>> s = "hello"
>> a = len(s)
>> id(a)
44
>> a = len(s)
>> id(a)
45

As you can see that, id()'s result is changed in every calls. In Python, however, not be changed.

In Python:

>> s = "hello"
>> a = len(s)
>> id(a)
2633845
>> a = len(s)
>> id(a)
2633845

I know id() function returns an object identification number(ID) of its single parameter. Why does two python interpreters give me a different result?

Kyokook Hwang
  • 2,682
  • 21
  • 36

2 Answers2

2

CPython has a cache of constant small integers that are used whenever needed. This pool of integers is an optimisation and improves the performance because a new object does not need to be allocated for every small integer as needed. Evidently IronPython handles this differently.

That said, the id() function returns a number which uniquely identifies an object. You can use this to see whether two names are bound to the same object. You cannot use this value to see whether two objects are "equal" in any sense.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    "in any sense" -> in general. Checking for equality with `None`, `True`, `False` or any other singleton with `is` is perfectly valid. – Fred Foo Oct 13 '11 at 08:12
  • @larsmans As your comment, **is** keyword is only able to used for None, True, False?? If I use like that "if len(a) is not 0:", is it wrong? – Kyokook Hwang Oct 13 '11 at 09:25
  • 1
    @KyokookHwang: yes, it's wrong. Python does not guarantee that `0 is 0`. Use `==` instead. – Fred Foo Oct 13 '11 at 10:28
  • @KyokookHwang: Please see [Python “is” operator behaves unexpectedly with integers](http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers) for more information on why that won't work. – Greg Hewgill Oct 13 '11 at 18:24
1

http://docs.python.org/library/functions.html#id

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.

Python implementation detail: This is the address of the object in memory.

Why do you think ids would be constant?

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • I really knew that the python assigns constant id to numeric value and constant character, such a invariant values. So, the value is determinately assigned to them. In other worlds, I was knowing that id is global value so far. – Kyokook Hwang Oct 13 '11 at 09:34
  • The fact that the value constant in CPython is just an implementation detail - it does not guarantee to behave that way. So in this case if one crow is black does not make the fact that all crows are black. – Mikko Ohtamaa Oct 13 '11 at 10:19