title: Traversing a Python object tree
body: <p>I'm trying to implement dynamic reloading objects in Python, that reflect code changes live.</p>
  
  <p>Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective.</p>
  
  <p>The problem is that objects data (objects <code>__dict__</code> content) is lost during the process.</p>
  
  <p>So I tried another approach:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>And surprisingly it works ! After calling refresh() on my objects, the new code becomes effective, without need to recreate them.</p>
  
  <p>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 ?</p>