id( ) function question

Mel mwilson at the-wire.com
Thu Oct 15 08:30:28 EDT 2009


Erik Max Francis wrote:
> Tim Chase wrote:
>> In general, if you're using "is" (and not comparing with None) or id(),
>> you're doing it wrong unless you already know the peculiarities of
>> Python's identity implementations.

> Right.  Another way to do look at it is that if you're curious about
> what the value of `id` is or how the `is` operator works, the short
> version is, don't worry about them, as you won't be using them.

As Python has evolved the semantics have got richer, and the implementation 
has got trickier with proxy objects and wrapped functions and more.  
Whatever use there was for `is` in ordinary code is vanishing.

Even a straight-up assignment can fool:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
...   def __init__ (self):
...     self.mangler = self.method1
...   def method1 (self):
...     return id (self) ^ 30103
...   def is_mangled (self):
...     return self.mangler is self.method1
... 
>>> a=A()
>>> a.is_mangled()
False

I fully understand that there's an excellent reason for that -- I wouldn't 
have it any other way.  Also note that, in the same example

>>> a.mangler == a.method1
True


My poster-child use of `is` is a MUDD game where 

`reference1_to_player is reference2_to_player` 

, if True, means that both refer to the same in-game player.  Even that 
might not last.

> I'm really rather surprised at the number of questions about them.
> They're really something one does not need to worry about.

Particularly to the newbie, `is` and `id` look like they ought to be good 
for *something*.  You have to know a lot about Python internals to know how 
little they mean.

Maybe the docs should have some kind of "Debugging and Introspection" 
dungeon that they could be thrown into.


	Mel.




More information about the Python-list mailing list