isinstance() not recognizing an instance correctly (python bug?)
Fernando Perez
fperez528 at yahoo.com
Wed May 8 00:49:38 EDT 2002
Hi all,
I've found a rather unpleasant situation where isinstance(obj,cls)==0, even
though obj _is_ indeed a cls() instance. I don't know if this should be
considered a bug or just an unavoidable consequence of the circumstances
where it happens.
As part of my IPython interactive interpreter shell, the system that takes
care of displaying results (a simple 'print' in the default case) can look
for certain classes. Now consider that interactively I do:
>>> from somemodule import someclass
>>> s=someclass()
>>> s
{ at this point, the system needs to print the object s }
In the printing code, suppose the display() function below is what gets
called:
from somemodule import someclass
...
def display(arg):
if isinstance(arg,someclass):
print_fancy(arg)
else:
print arg
Well, when 's' above is passed to display(), it fails to identify that s is
indeed an instance of someclass(). The reason, I think, is that the
interactive code is executed in a separate namespace than the display code,
and therefore someclass exists with two different memory addresses. So maybe
there's just no way out of the problem.
But I think it's a subtle enough 'surprising behavior' that it should at least
be mentioned in the docs that 'isinstance(i,c) returns true if i is an
instance of class c, except when it gets confused and gives the wrong answer.
Use it and hope for the best.' ;)
Seriously though, while somewhat particular the circumstances where it fails
aren't really that strange, and this failure mode should definitely be
documented, if not considered a bug.
Cheers,
f.
More information about the Python-list
mailing list