id( ) function question

Christian Heimes lists at cheimes.de
Thu Oct 15 11:57:26 EDT 2009


Mel wrote:
> 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.

'is' has important use cases but it's not trivial to use if you leave
the road.

> 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

Even "obj.method is obj.method" doesn't return true because Python
creates a new method wrapper for every attribute access:

>>> class Example(object):
...     def func(self):
...         pass
...
>>> Example.func
<unbound method Example.func>
>>> Example.func is Example.func
False


Christian




More information about the Python-list mailing list