I'm trying to implement dynamic reloading objects in Python, that reflect code changes live.
Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective.
The problem is that objects data (objects __dict__
content) is lost during the process.
So I tried another approach:
def refresh(obj, memo=None):
if memo is None:
memo = {}
d = id(obj)
if d in memo:
return
memo[d] = None
try:
obj.__class__ = getattr(sys.modules[obj.__class__.__module__],
obj.__class__.__name__)
except TypeError:
return
for item in obj.__dict__.itervalues():
if isinstance(item, dict):
for k, v in item.iteritems():
refresh(k, memo)
refresh(v, memo)
elif isinstance(item, (list, tuple)):
for v in item:
refresh(v, memo)
else:
refresh(item, memo)
And surprisingly it works ! After calling refresh() on my objects, the new code becomes effective, without need to recreate them.
But I'm not sure if this is the correct way to traverse an object ? Is there a better way to traverse an object's components ?