I am running an interactive python session which builds big python data-structures (5+ GB) which take a long time to load, and so I want to exploit Python on-the-fly code change abilities at its maximum (though sometimes, without having to plan too much for that).
My current problem is the following: I have an old instance of a class that I have later modified the code and reloaded the module — I would like the old instance to be able to use the new function definitions. How do I do that without just manually copying all the information from the old instance to a new fresh instance?
Here is what I have tried. Suppose I have the module M.py:
class A():
def f(self):
print "old class"
Here is an interactive session:
import M
old_a = M.a()
# [suppose now I change the definition of M.A.f in the source file]
reload(M)
# I attempt to use the new class definition with the old instance:
M.A.f(old_a)
at which point I get the following type error from Python:
TypeError: unbound method f() must be called with A instance as first argument (got A instance instead)
Python is obviously not happy to receive an old instance of A even though they are basically functionally equivalent types (in my code) — is there any way I could ‘type cast’ it to the new instance type so that Python wouldn’t complain? Something morally like: M.A.f( (M.A) old_a ) ?
There is no casting in Python but you can change the class of an existing object: It is perfectly legal and does the job:
As long as you haven’t changed the relation between class methods and instance variables, changed what
__init__does or something like that this is perfectly fine.EDIT: As
jsbuenopoints out: The__init__or__new__methods are not called at the point of changing__class__. Further, the new__del__will be called at destruction.