Python – Traversing a Python object tree

pythonreloadtraversal

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 ?

Best Solution

See this recipe in the Python Cookbook (or maybe even better its version in the "printed" one, which I believe you can actually read for free with google book search, or for sure on O'Reilly's "Safari" site using a free 1-week trial subscription -- I did a lot of editing on Hudson's original recipe to get the "printed book" version!).