Recursively dump an object

Your code works for me, except that things get printed in the wrong order (inner first, which is what I actually would expect with recursion).

So, I changed the order (and used isinstance() as well as iterating over the __dict__):

import types

def dump_obj(obj, level=0):
    for key, value in obj.__dict__.items():
        if not isinstance(value, types.InstanceType):
             print " " * level + "%s -> %s" % (key, value)
        else:
            dump_obj(value, level + 2)

class B:
  def __init__ (self):
    self.txt = 'bye'

class A:
  def __init__(self):
    self.txt = 'hello'
    self.b = B()

a = A()

dump_obj(a)

produces

txt -> hello
  txt -> bye

This will recursively dump any object and all sub-objects. The other answers worked for simple examples, but for complex objects, they were missing some data.

import jsonpickle # pip install jsonpickle
import json

serialized = jsonpickle.encode(obj)
print(json.dumps(json.loads(serialized), indent=2))

EDIT: If you use YAML format, it will be even closer to your example.

import yaml # pip install pyyaml
print(yaml.dump(yaml.load(serialized), indent=2))

Tags:

Python