Skip to content

Instantly share code, notes, and snippets.

@techtonik
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techtonik/adf24ac84b8fdc46c8af to your computer and use it in GitHub Desktop.
Save techtonik/adf24ac84b8fdc46c8af to your computer and use it in GitHub Desktop.
Blueprint for dumper of Python variables
"""
The code is placed in to public domain by
anatoly techtonik <techtonik@gmail.com>
Produce readable representation of variable content,
including custom properties for complex objects.
Needed features:
[ ] easy import
[ ] sane defaults
[ ] print to screen (stdout)
[ ] don't show internal __ fields
[ ] indent nested structures
[ ] detect loops
[ ] output to different stream with .write method
[ ] output to string
[ ] colorize if possible
"There should be one-- and preferably only one --obvious way to do it."
Methods.
https://stackoverflow.com/questions/192109/is-there-a-function-in-python-to-print-all-the-current-properties-and-values-of
1. print obj.__dict__
Advantages: returns key and value, which allows to inspect value directly.
Fail: Not all objects have __dict__ attribute, for example set.
2. print vars(obj)
Same fail as above. "TypeError: vars() argument must have __dict__ attribute".
3. print dir(obj)
Seems to always work (unless user botched __dir__ method in their class).
Returns only names, so need to make a separate lookup call [ ] to fetch
values and their types. The lookup call may trigger additional logic.
4. inspect.getmembers()
"""
import inspect
import sys
def dumpvar(obj, _indent=0, _writeto=sys.stdout):
_writeto.write(' '*_indent + type(obj).__name__ + '\n')
for name, value in inspect.getmembers(obj):
# [x] filter standard __ symbols
# [ ] filter non-overriden __ symbols
if not name.startswith('__'):
_writeto.write(' '*(_indent+2) + name + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment