python - Recursively dump an object -
i not sure if there standard way of doing this. have implemented following function dump contents of object. must recursively dump sub-objects, checking instancetype
, not work:
import types def dump_obj(obj, level=0): 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 can verify if element object?
what want following. given:
class b: def __init__(self): self.txt = 'bye' class a: def __init__(self): self.txt = 'hello' self.b = b() = a() dump_obj(a)
i want following output:
txt -> hello txt -> bye
it better use isinstance(x, y)
instead of type(x) == y
.
since object in python, doesn't make sense isinstance(attr, object)
, because (i guess) returns true.
your best bet "blacklist" types. example, check if it's other int, float, str, unicode, list, dict, set, ...
go deeper, otherwise print it.
for example:
def dump(obj, level=0): attr 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 account inheritance, if try see if object instance of parent class, return true while may not when using type.
since in case you'll testing against primitive types, may not make difference in case, in general isinstance
preferable.
see example:
>>> class a(object): pass ... >>> class b(a): pass ... >>> a, b = a(), b() >>> type(a) <class '__main__.a'> >>> type(a) == true >>> type(b) <class '__main__.b'> >>> type(b) == b true >>> type(b) == false >>>
you can check out docs
Comments
Post a Comment