confused by isinstance()
Francois Petitjean
littlejohn.75 at free.fr
Fri Feb 1 01:20:55 EST 2002
>You'll either need to post more code or reduce the code
Here is a trivial script (1) which highlights the problem :
#!/usr/bin/env python
"""Fake Foo python module to test isinstance"""
class Foo:
def __init__(self):
print "ctor " #,foo(self)
def foo(o):
return isinstance(o,Foo)
def bar(o, modname='Foo'):
"""is o an instance of the class Foo in a module named modname"""
mymod = __import__(modname) # or import Foo as mymod
cls = mymod.Foo
print "bar(o) %s %s" % ( isinstance(o,cls), `cls`)
print "names? %s" % ( cls.__name__ == o.__class__.__name__, )
if __name__ == '__main__':
x = Foo()
bar(x)
print "foo(o) %s %s" % (foo(x), `Foo`)
print "names? %s" % ( Foo.__name__ == x.__class__.__name__, )
print `x`
the output: (python 2.1.1 Windows NT4)
$ ../Python21/python.exe Foo.py
ctor
bar(o) 0 <class Foo.Foo at 007CBABC>
names? 1
foo(o) 1 <class __main__.Foo at 007FCF9C>
names? 1
<__main__.Foo instance at 007FC2CC>
This, IMHO, shows the "insistance" of "isinstance" to be very picky about
its arguments. Or there is a pitfall in the handling of namespaces or
import semantics which I don't know?
Note that I am very aware that using isinstance or other type checking
should be avoided if possible. But, I want eagerly to understand.
(1) It is trivial as it has :
only one module
only one class
only one instance
and it uses only builtins and doesn't use 2.2 features.
TIA
More information about the Python-list
mailing list