bug with isinstance() ?

John Machin sjmachin at lexicon.net
Wed Jun 1 18:46:30 EDT 2005


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

Yes, it has the multi-module nature. What it needs, though, is the 
Buddha nature :-)

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

'print' and 'repr()' are your friends. Use them.
Add this:
print '*** Have just made class Foo:', repr(Foo)

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

Add these lines:
     print 'foo is an instance of', foo.__class__
     print 'In test, Foo is', repr(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():

Add this:
print "In test2, Foo is", repr(Foo)

>     return Foo()
> 
> 
> --8<--
> 
> When I run "python test.py", I get "is  NOT  a Foo!", when the object
> clearly IS a Foo!

Indeed foo is an instance of a class named Foo, but it is not the Foo 
you are looking for. You have created *TWO* Foo classes. A class is 
created when its source is executed. This has happened twice, once when 
you ran the test.py script, and again when test2.py imported test.

Circular imports are big trouble (in any language). If you think you 
need them, you are wrong; refactor until they go away. Circularly 
importing all or some objects from your __main__ script is double trouble.

HTH,

John



More information about the Python-list mailing list