Discard an object recursively

I am not sure if there is a standard way to do this. I performed the following function to reset the entire contents of an object. It should recursively unload sub-objects, so I check InstanceType , but it does not work:

 import types def dump_obj(obj, level=0): for a in dir(obj): try: if type(obj.__dict__[a]) == types.InstanceType: dump_obj(obj.__dict__[a], level + 2) else: try: print " " * level + "%s -> %s" % (a, obj.__dict__[a]) except: pass except: pass 

How to check if an element is an object itself?

What I really want is the following. Given:

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

I need the following output:

 txt -> hello txt -> bye 
+10
source share
3 answers

It is always better to use isinstance(x, y) instead of type(x) == y .

Since everything is an object in Python, isinstance(attr, object) does not make sense, because (I think) it always returns true.

It’s best to blacklist certain types. For example, you check if it goes further than int, float, str, unicode, list, dict, set, ... , otherwise you just print it.

For example:

 def dump(obj, level=0): for a in dir(obj): val = getattr(obj, a) if isinstance(val, (int, float, str, unicode, list, dict, set)): print level*' ', val else: dump(val, level=level+1) 

UPDATE : isinstance takes into account inheritance, so if you try to see if the object is an instance of the parent class, it will return True, or maybe not when using the type.

Since in this case you will test primitive types, in this case it may not make any difference, but in general isinstance preferable.

Check out this example:

 >>> class A(object): pass ... >>> class B(A): pass ... >>> a, b = A(), B() >>> type(a) <class '__main__.A'> >>> type(a) == A True >>> type(b) <class '__main__.B'> >>> type(b) == B True >>> type(b) == A False >>> 

You can check the documents

+2
source

This will recursively flush any object and all subobjects. Other answers worked for simple examples, but for complex objects, they lacked some data.

 import jsonpickle # pip install jsonpickle import json serialized = jsonpickle.encode(obj) print(json.dumps(json.loads(serialized), indent=2)) 

UPDATE: if you use the YAML format, it will be even closer to your example.

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

Your code works for me, except that things print in the wrong order (first, first, what would I expect with recursion).

So, I changed the order (and used isinstance() , as well as iterating over __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 
+7
source

All Articles