Skip to content

Instantly share code, notes, and snippets.

@KillerGoldFisch
Last active December 17, 2015 22:49
Show Gist options
  • Save KillerGoldFisch/5685066 to your computer and use it in GitHub Desktop.
Save KillerGoldFisch/5685066 to your computer and use it in GitHub Desktop.
Dump object structure in Python and Jython
__author__ = "Kevin Gliewe"
__copyright__ = "Copyright 2015, Kevin Gliewe"
__credits__ = ["Kevin Gliewe"]
__license__ = "WTFPL"
__version__ = "1.0.1"
__maintainer__ = "Kevin Gliewe"
__email__ = "kevingliewe@gmail.com"
__status__ = "Production"
"""
Copyright (C) 2015 Kevin Gliewe <kevingliewe@gmail.com>
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
Usage:
# Dump to Console
pdump(anobject, depth)
# Dump to String
s = sdump(anobject, depth)
"""
import sys
primitive = (int, str, bool, float)
_errors = [Exception]
if sys.subversion[0] =="Jython":
import java.lang.Error, java.lang.Exception
_errors.append(java.lang.Error)
_errors.append(java.lang.Exception)
elif sys.subversion[0] == "CPython":
pass
_errors = tuple(_errors)
def pdump(obj, maxdepth=1, depth=0, **args):
import pprint
pprint.pprint(dump(obj, maxdepth, 0, **args))
def sdump(obj, maxdepth=1, depth=0, **args):
import pprint
return pprint.pformat(dump(obj, maxdepth, 0, **args))
def dump(obj, maxdepth=1, depth=0, **args):
import inspect
if depth > maxdepth:
raise Exception("exceeded max depth")
if args.has_key("verbose"):
if args["verbose"]:
print depth*"##" + "Enter Dump '%s' in depth %i"%( str(obj), depth)
try:
if hasattr(obj, '__call__') or inspect.isfunction(obj):
dumpMethod = dumpFunction
elif isinstance(obj, list):
dumpMethod = dumpArray
elif isinstance(obj, tuple):
dumpMethod = dumpTuple
elif isinstance(obj, dict) or type(obj).__name__ == "dict":
dumpMethod = dumpDict
elif isinstance(obj, primitive):
dumpMethod = dumpPrimitive
else:
dumpMethod = dumpObject
if args.has_key("verbose"):
if args["verbose"]:
print depth*"##" + "Call '%s' at '%s' in depth %i"%(str(dumpFunction(dumpMethod)), str(obj), depth)
return dumpMethod(obj, maxdepth, depth, **args)
except _errors, ex:
if args.has_key("verbose"):
if args["verbose"]:
print depth*"##" + "Exception '%s' at '%s' in depth %i"%(str(ex), str(obj), depth)
return obj
def dumpArray(arr, maxdepth = 1, depth = 0, **args):
if depth > maxdepth:
raise Exception("exceeded max depth")
returnArr = []
for val in arr:
returnArr.append(dump(val, maxdepth, depth + 1, **args))
return returnArr
def dumpTuple(arr, maxdepth = 1, depth = 0, **args):
if depth > maxdepth:
raise Exception("exceeded max depth")
return tuple(dumpArray(arr, maxdepth, depth))
def dumpDict(arr, maxdepth = 1, depth = 0, **args):
if depth > maxdepth:
raise Exception("exceeded max depth")
returnDict = {}
for key in arr.keys():
returnDict[key] = dump(arr[key], maxdepth, depth + 1, **args)
return returnDict
def dumpPrimitive(obj, maxdepth = 1, depth = 0, **args):
return obj #str(obj)
def dumpFunction(val, maxdepth = 1, depth = 0, **args):
#if depth > maxdepth:
# raise Exception("exceeded max depth")
import inspect
returnstring = ""
returnstring = str(val) + " " + str(val.func_globals["__name__"]) + "." + str(val.__name__)
try:
argSpec = inspect.getargspec(val)
argList = []
for n in range(len(argSpec.args)):
argStr = argSpec.args[n]
if len(argSpec.args) - n <= len(argSpec.defaults):
argStr += "=" + str(argSpec.defaults[-n - len(argSpec.defaults) + len(argSpec.args)])
argList.append(argStr)
returnstring+= "(" + ", ".join(argList)
if argSpec.varargs != None:
returnstring+=", *"+argSpec.varargs
if argSpec.keywords != None:
returnstring+=", **"+argSpec.keywords
returnstring+=")"
except _errors, ex:
if args.has_key("verbose"):
if args["verbose"]:
print depth*"##" + "FunctionException '%s' at '%s' in depth %i"%(str(ex), str(val), depth)
if val.__doc__ != None:
returnstring+=" -> " + val.__doc__
return returnstring
def dumpObject(obj, maxdepth = 1, depth = 0, **args):
if depth > maxdepth:
raise Exception("exceeded max depth")
dumpDic = {}
import inspect
dumpDic["__type__"] = type(obj).__name__
dumpDic["__module__"] = inspect.getmodule(obj)
for key in dir(obj):
if key.startswith("__") and not key == "__class__":
if args.has_key("ignoreprivate"):
if args["ignoreprivate"]:
continue
else:
continue
try:
val = obj.__getattribute__(key)
dumpDic[key]=val
dumpDic[key] = dump(val, maxdepth,depth + 1, **args)
except _errors, ex:
if args.has_key("verbose"):
if args["verbose"]:
print depth*"##" + "AttributeException '%s' at '%s' in depth %i"%(str(ex), str(val), depth)
return dumpDic
def main():
def method(a,b,c=42,*asd,**asdf):
return 42 + a
class stdClass(object):
def test():
pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.methon = method
obj.subObj=stdClass()
obj.subObj.value='foobar'
pdump(obj,6,ignoreprivate=False)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment