Is " a is b " and " id(a) == id(b) " the same?

Alex Martelli aleax at aleax.it
Sun Mar 16 11:14:47 EST 2003


Chen wrote:

> "Alex Martelli" <aleax at aleax.it> wrote in message
> news:LNVca.64538$pG1.1493379 at news1.tin.it...
>> Your observation is correct, and shows this common assertion needs
>> one extra qualification: "provided objects a and b are alive while
>> the whole operation is taking place".  This in turn comes from two
>> Python characteristics:
> 
> Thanks for your excellent explanation! I learned much. :-)
> 
> And add another interesting example for it:
> 
>>>> print a.f is a.f
> False
> 
> Wow! :-)

Yep -- you can also explicitly define attributes that are generated
on the fly at each access and ensure this behavior (method objects
currently _are_ generated on the fly at each access, but it's quite
permissible for the language implementation to change and cache them
in some cases in the future).  E.g., try:

class X(object):
    def __getattr__(self, name):
        if name == 'f': return []
        raise AttributeError, name

or

class Y(object):
    def getf(self): return []
    f = property(getf)

NOW, after a=X() or a=Y(), you can choose to:

    assert a.f is not a.f

and be _entirely_ sure this will never raise an AssertionError.


Alex





More information about the Python-list mailing list