How can I recursively print the contents of a variable, including both the data and object attributes?
可用于打印Python变量的含量。但变量的含量可能是复杂的。图书馆,作为PHP EDOCX1〕〔3〕报告,在阅读方便的格式中,为显示Just Data而作的工作是平衡的:什么是PHP Var dump(?)复制这个网站码到您的网站上以设置一个投票箱在您的网站上。
然而,如果数据中有任何物体([edit]that haven't implemented
某些功能,如建筑物,不应印刷为不使用。该方法还应能处理诸如
我在下面打了一枪不认为它不工作,但我确信,有边缘案例不为输出而核对,而且可能有一些信息丢失(E.G.Distinguish Tuples/Lists)。我要说的是,请分享另一种选择:)
这将以JSON或YAML(选择)缩进格式递归打印所有对象内容:
1 2 3 4 5 6 7 | import jsonpickle # pip install jsonpickle import json import yaml # pip install pyyaml serialized = jsonpickle.encode(obj) print json.dumps(json.loads(serialized), indent=4) print yaml.dump(yaml.load(serialized), indent=4) |
这是我的答案。就我的目的而言,这是非常有效的,但我再次确认,有更有效的方法来实现这一点。如果你有更好的方法,请分享:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import types def var_dump(obj, depth=4, l=""): #fall back to repr if depth<0: return repr(obj) #expand/recurse dict if isinstance(obj, dict): name ="" objdict = obj else: #if basic type, or list thereof, just print canprint=lambda o:isinstance(o, (int, float, str, unicode, bool, types.NoneType, types.LambdaType)) try: if canprint(obj) or sum(not canprint(o) for o in obj) == 0: return repr(obj) except TypeError, e: pass #try to iterate as if obj were a list try: return"[ " +" ".join(l + var_dump(k, depth=depth-1, l=l+" ") +"," for k in obj) +" " + l +"]" except TypeError, e: #else, expand/recurse object attribs name = (hasattr(obj, '__class__') and obj.__class__.__name__ or type(obj).__name__) objdict = {} for a in dir(obj): if a[:2] !="__" and (not hasattr(obj, a) or not hasattr(getattr(obj, a), '__call__')): try: objdict[a] = getattr(obj, a) except Exception, e: objdict[a] = str(e) return name +"{ " +" ".join(l + repr(k) +":" + var_dump(v, depth=depth-1, l=l+" ") +"," for k, v in objdict.iteritems()) +" " + l +"}" |
示例输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class B(object): mystatic = [1,2,3] class A: mystatic ="hello" def __init__(self): self.mymember1 = B() self.mymember2 = B(), 123.4,"world" def myfunc(self): print"hi" var = {"foo": A(),"bar": B()} ... >>> print var_dump(var) { 'foo': A{ 'mystatic': 'hello', 'mymember1': B{ 'mystatic': [1, 2, 3], }, 'mymember2': [ B{ 'mystatic': [1, 2, 3], }, 123.4, 'world', ], }, 'bar': B{ 'mystatic': [1, 2, 3], }, } |
号
我最初写这个是因为Django的调试工具栏使用了