Paste P7836

var_dump.py
ActivePublic

Authored by mmodell on Wed, Nov 21, 6:23 PM.
import json
import pygments
import pygments.lexers
import pygments.formatters
from json import JSONEncoder
class VarDumpJSONEncoder(JSONEncoder):
''' encode python objects to json '''
def default(self, o):
if hasattr(o, '__dump__'):
return o.__dump__()
if hasattr(o, '__dict__'):
return o.__dict__
try:
return JSONEncoder.default(self, o)
except (TypeError, ValueError):
return "Unserializable"
def var_dump(*args, **kwargs):
''' dump an object to the console as pretty-printed json'''
lexer = pygments.lexers.JsonLexer()
formatter = pygments.formatters.TerminalFormatter()
encoder = VarDumpJSONEncoder(indent=2)
def dump(obj):
try:
json_str = encoder.encode(obj)
output = pygments.highlight(json_str, lexer, formatter)
print(output)
except Exception as e:
print(e)
print(obj)
for arg in args:
dump(arg)
if kwargs:
dump(kwargs.items())