bug with isinstance() ?

Terry Reedy tjreedy at udel.edu
Wed Jun 1 17:31:50 EDT 2005


"Mac" <idontneednostinkinid at yahoo.com> wrote in message 
news:1117657881.206934.289600 at g14g2000cwa.googlegroups.com...
> Under certain circumstances isinstance() seems to return incorrect
> value for me.  I'm using Python 2.3 (latest from Debian's unstable).
> Here's a sample program... the multi-module nature of the code is key.

The key, which my debug addition below should help you see, is a 
consequence of the mutually recursive definitions of the two modules, with 
one of them also being the main module.  This is a recipe for confusing 
results that is best avoided.  But I believe you could also get the same 
confusing result with one file that imported itself directly rather than 
indirectly via a second file.

> === test.py ===
>
> class Foo:
>    pass

> def test():
>    from test2 import make_me_a_foo
>    foo = make_me_a_foo()

Try adding
     print id(foo.__class__), foo.__class__
     print id(Foo), Foo

>    if isinstance(foo, Foo):
>        print "is a Foo"
>    else:
>        print "is  NOT  a Foo!"
>
> if __name__ == "__main__":
>    test()

> === test2.py ===
>
> from test import Foo
>
> def make_me_a_foo():
>    return Foo()

> When I run "python test.py", I get "is  NOT  a Foo!", when the object
> clearly IS a Foo!  Am I missing something

Yes, the ambiguity of Foo, which the print statements should reveal. 
Deriving Foo from object to make it newstyle should give similar behavior.

> or is this a bug?

Pretty sure not.  It is hard to go wrong comparing ids for equality.

Terry J. Reedy






More information about the Python-list mailing list