When debugging in PHP, I frequently find it useful to simply stick a var_dump() in my code to show me what a variable is, what its value is, and the same for anything that it contains.
What is a good Python equivalent for this?
So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.
def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
Here is the usage
class stdClass(object): 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.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
and the results.
{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.
GitHub: https://github.com/sha256/python-var-dump
You can simply install it using pip
:
pip install var_dump
print
For your own classes, just def a __str__
method
The closest thing to PHP's var_dump()
is pprint()
with the getmembers()
function in the built-in inspect
module:
from inspect import getmembers
from pprint import pprint
pprint(getmembers(yourObj))
PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"
Old topic, but worth a try.
Here is a simple and efficient var_dump
function:
def var_dump(var, prefix=''):
"""
You know you're a php developer when the first thing you ask for
when learning a new language is 'Where's var_dump?????'
"""
my_type = '[' + var.__class__.__name__ + '(' + str(len(var)) + ')]:'
print(prefix, my_type, sep='')
prefix += ' '
for i in var:
if type(i) in (list, tuple, dict, set):
var_dump(i, prefix)
else:
if isinstance(var, dict):
print(prefix, i, ': (', var[i].__class__.__name__, ') ', var[i], sep='')
else:
print(prefix, '(', i.__class__.__name__, ') ', i, sep='')
Sample output:
>>> var_dump(zen)
[list(9)]:
(str) hello
(int) 3
(int) 43
(int) 2
(str) goodbye
[list(3)]:
(str) hey
(str) oh
[tuple(3)]:
(str) jij
(str) llll
(str) iojfi
(str) call
(str) me
[list(7)]:
(str) coucou
[dict(2)]:
oKey: (str) oValue
key: (str) value
(str) this
[list(4)]:
(str) a
(str) new
(str) nested
(str) list
So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.
def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
Here is the usage
class stdClass(object): 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.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
and the results.
{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"
I don't have PHP experience, but I have an understanding of the Python standard library.
For your purposes, Python has several methods:
logging module;
Object serialization module which is called pickle. You may write your own wrapper of the pickle module.
If your using var_dump
for testing, Python has its own doctest and unittest modules. It's very simple and fast for design.
print
For your own classes, just def a __str__
method
PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"
print
For your own classes, just def a __str__
method
I use self-written Printer class, but dir() is also good for outputting the instance fields/values.
class Printer:
def __init__ (self, PrintableClass):
for name in dir(PrintableClass):
value = getattr(PrintableClass,name)
if '_' not in str(name).join(str(value)):
print ' .%s: %r' % (name, value)
The sample of usage:
Printer(MyClass)
So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.
def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
Here is the usage
class stdClass(object): 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.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
and the results.
{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
PHP's var_export() usually shows a serialized version of the object that can be exec()'d to re-create the object. The closest thing to that in Python is repr()
"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]"
So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.
def dump(obj):
'''return a printable representation of an object for debugging'''
newobj=obj
if '__dict__' in dir(obj):
newobj=obj.__dict__
if ' object at ' in str(obj) and not newobj.has_key('__type__'):
newobj['__type__']=str(obj)
for attr in newobj:
newobj[attr]=dump(newobj[attr])
return newobj
Here is the usage
class stdClass(object): 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.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
and the results.
{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
The closest thing to PHP's var_dump()
is pprint()
with the getmembers()
function in the built-in inspect
module:
from inspect import getmembers
from pprint import pprint
pprint(getmembers(yourObj))
I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.
GitHub: https://github.com/sha256/python-var-dump
You can simply install it using pip
:
pip install var_dump
Old topic, but worth a try.
Here is a simple and efficient var_dump
function:
def var_dump(var, prefix=''):
"""
You know you're a php developer when the first thing you ask for
when learning a new language is 'Where's var_dump?????'
"""
my_type = '[' + var.__class__.__name__ + '(' + str(len(var)) + ')]:'
print(prefix, my_type, sep='')
prefix += ' '
for i in var:
if type(i) in (list, tuple, dict, set):
var_dump(i, prefix)
else:
if isinstance(var, dict):
print(prefix, i, ': (', var[i].__class__.__name__, ') ', var[i], sep='')
else:
print(prefix, '(', i.__class__.__name__, ') ', i, sep='')
Sample output:
>>> var_dump(zen)
[list(9)]:
(str) hello
(int) 3
(int) 43
(int) 2
(str) goodbye
[list(3)]:
(str) hey
(str) oh
[tuple(3)]:
(str) jij
(str) llll
(str) iojfi
(str) call
(str) me
[list(7)]:
(str) coucou
[dict(2)]:
oKey: (str) oValue
key: (str) value
(str) this
[list(4)]:
(str) a
(str) new
(str) nested
(str) list
I don't have PHP experience, but I have an understanding of the Python standard library.
For your purposes, Python has several methods:
logging module;
Object serialization module which is called pickle. You may write your own wrapper of the pickle module.
If your using var_dump
for testing, Python has its own doctest and unittest modules. It's very simple and fast for design.
I use self-written Printer class, but dir() is also good for outputting the instance fields/values.
class Printer:
def __init__ (self, PrintableClass):
for name in dir(PrintableClass):
value = getattr(PrintableClass,name)
if '_' not in str(name).join(str(value)):
print ' .%s: %r' % (name, value)
The sample of usage:
Printer(MyClass)
print
For your own classes, just def a __str__
method
Source: Stackoverflow.com