Skip to content

Instantly share code, notes, and snippets.

@wware
Last active June 2, 2016 18:30
Show Gist options
  • Save wware/de694ef53ceb67840ddc to your computer and use it in GitHub Desktop.
Save wware/de694ef53ceb67840ddc to your computer and use it in GitHub Desktop.
Yet another attempt to write a useful var_dump for Python
import pprint
import logging
def about(thang):
def shorty(x):
if len(x) > 200:
x = x[:200] + "..."
return x
if isinstance(thang, dict):
info = dict([(x, shorty(repr(thang.get(x)))) for x in thang.keys()])
else:
info = dict([(x, shorty(repr(getattr(thang, x)))) for x in dir(thang)
if not x.startswith("_")])
import pprint
return pprint.pformat(info)
def _is_primitive(obj):
return (
isinstance(obj, int) or
isinstance(obj, float) or
isinstance(obj, complex) or
isinstance(obj, str) or
isinstance(obj, unicode) or
isinstance(obj, bool)
)
def dig(obj, n, hack_kv=None, base=''):
"""
Dig through an object looking for a particular thing. I think this might
be useful in providing arguments to mock.patch, because those things are
always kinda non-obvious.
"""
if n == 0:
return
if obj is None:
return
if hack_kv is None:
# pylint: disable=function-redefined
def hack_kv(key, strkey, subobj):
print strkey, '=>', repr(subobj)
return _is_primitive(subobj)
# pylint: enable=function-redefined
if isinstance(obj, list) or isinstance(obj, tuple):
iterable = range(len(obj))
selector = lambda k, obj=obj: obj[k]
fmt = "[{0}]"
elif isinstance(obj, dict):
iterable = [k for k in obj.keys() if not k.startswith('__')]
selector = lambda k, obj=obj: obj.get(k)
fmt = '["{0}"]'
else:
iterable = [k for k in dir(obj) if not k.startswith('__')]
selector = lambda k, obj=obj: getattr(obj, k)
fmt = ".{0}"
for k in iterable:
if base:
s = base + fmt.format(k)
else:
s = str(k)
y = selector(k)
if not hack_kv(k, s, y):
try:
dig(y, n - 1, hack_kv, s)
except:
pass
if __name__ == '__main__':
# quick dumb test
def foo(k, obj, s):
if k != 'func_globals':
print s, '=>', obj
dig(sys, 3, foo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment