reloading modules and isinstance()
Diez B. Roggisch
deets at nospam.web.de
Tue Dec 4 09:41:48 EST 2007
Tlis wrote:
> I am using a software system with an embedded Python interpreter
> (version 2.3) for scripting. The KcsPoint2D.py module contains a
> Point2D class with the following method:
>
> def SetFromMidpoint(self, p1, p2):
> if not isinstance(p1, Point2D) or not isinstance(p2, Point2D):
> raise TypeError, 'some error message'
> ---
>
> The problem is that after I launch my script once, and then use the
> 'Reload modules' button (presumably it calls reload() on all loaded
> modules), the isinstance() tests shown above fails, even though the
> expressions:
>
> type(self)
> type(p1)
> type(p2)
>
> all show: class 'KcsPoint2D.Point2D'
>
> Could you explain, please what is going on? Why the isinstance()
> function returns False?
You just discovered one reason why reload() is a bad idea and IMHO shouldn't
be used at all - as tempting it might be.
Reload will re-execute the importing of the module and perform all necessary
initializations there, overwrite names in the module namespace and such.
But it _won't_ magically change classes or other objects being referred to
from other code that have been created prior to the reloading. Consider
this example:
class A(object):
foo = 10
a = A()
class A(object):
foo = 20
print a.foo
>>> 10
All that happens is that the name A is bound to a new class. So all
subsequent instantiations are of the new type. But not the old instances -
because the refer to their class not by NAME, but just have a pointer to
it.
Diez
More information about the Python-list
mailing list