Another of those "is" issues.

Steve Holden steve at holdenweb.com
Fri Mar 20 14:48:41 EDT 2009


Emanuele D'Arrigo wrote:
> Hi everybody,
> 
> I was unit testing some code today and I eventually stumbled on one of
> those "is" issues quickly solved replacing the "is" with "==". Still,
> I don't quite see the sense of why these two cases are different:
> 
>>>> def aFunction():
> ...     pass
> ...
>>>> f = aFunction
>>>> f is aFunction

In fact, for any defined unqualified name x the assignment "n = x"
guarantees that "n is x" is True.

> True   <--- Ok, this seems reasonable. Nevertheless, I suspect I
> shouldn't quite rely on it.
> 
You can take that to the bank on any working Python implementation. It's
hardwired into the language's semantics.

>>>> class MyClass(object):
> ...     def myMethod(self):
> ...         pass
> ...
>>>> c = MyClass()
>>>> m = c.myMethod
>>>> m is c.myMethod
> False  <--- What? Why is that?
> 
> In my mind I was expecting that when the method is assigned to "m" all
> that it happens is that its address is assigned to the name "m" so
> that effectively the same address is now pointed to by two names, like
> in the function case. I googled around for some hint but I wouldn't
> exactly say I'm clear on the issue just yet...
> 
> Can anybody shed some light? Or point to a resource to look at? Or
> what's the bit of python's source code that is responsible for dealing
> with those assignments?
> 
Instance-relative references to class methods are a very special case.
They become what are called "bound methods" - the interpreter creates a
new bound method for each reference.

This allows the bound method to provide the instance as a first argument
when it is called.

>>> class C(object):
...   def MyMethod(self):
...     pass
...
>>> c = C()
>>> a = c.MyMethod
>>> b = c.MyMethod
>>> a, b
(<bound method C.MyMethod of <__main__.C object at 0x7ff33fcc>>, <bound
method C.MyMethod of <__main__.C object at 0x7ff33fcc>>)
>>>

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
Holden Web LLC                 http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/




More information about the Python-list mailing list