Another of those "is" issues.
tjreedy at udel.edu
Fri Mar 20 23:09:48 CET 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
> True <--- Ok, this seems reasonable. Nevertheless, I suspect I
> shouldn't quite rely on it.
>>>> class MyClass(object):
> ... def myMethod(self):
> ... pass
>>>> c = MyClass()
>>>> m = c.myMethod
>>>> m is c.myMethod
> False <--- What? Why is that?
Compare that to MyClass.myMethod is MyClass.myMethod, which is True at
least in 3.0. Repeated attribute accesses may or may not return the
same object. Remember that class (and instance) attributes can be
computed properties, or produced by whatever means in __getattr__.
Also, x.a = b; x.a==b may or may not return True as the setting might be
intercepted by __setattr__.
More information about the Python-list