is implemented with id ?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Sep 5 05:14:23 EDT 2012
On Wed, 05 Sep 2012 08:30:31 +0200, Franck Ditter wrote:
> Hi !
> a is b <==> id(a) == id(b) in builtin classes. Is that true ?
Not just for builtin classes, for any objects, provided that they are
alive at the same time.
There is no guarantee whether IDs will be re-used. Some versions of
Python do re-use IDs, e.g. CPython:
steve at runes:~$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ["some", "object"]
>>> id(a)
3074285228L
>>> del a
>>> b = [100, 200]
>>> id(b)
3074285228L
but others do not, e.g. Jython and IronPython:
steve at runes:~$ jython
Jython 2.5.1+ (Release_2_5_1, Aug 4 2010, 07:18:19)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.6.0_18
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ["some", "object"]
>>> id(a)
1
>>> del a
>>> b = [100, 200]
>>> id(b)
2
steve at runes:~$ ipy
IronPython 2.6 Beta 2 DEBUG (2.6.0.20) on .NET 2.0.50727.1433
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ["some", "object"]
>>> id(a)
43
>>> del a
>>> b = [100, 200]
>>> id(b)
44
CPython especially has the most complicated behaviour with IDs and object
identity:
>>> a = 99.99
>>> b = 99.99
>>> a is b
False
>>> a = 99.99; b = 99.99; a is b
True
In general, you almost never need to care about IDs and object identity.
The main exception is testing for None, which should always be written as:
if x is None
--
Steven
More information about the Python-list
mailing list