What is a Python equivalent of PHP's var_dump()?


Question

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?

1
394
5/14/2014 7:00:08 PM

Accepted Answer

To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do

from pprint import pprint

pprint(globals())
pprint(locals())

If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.

257
3/24/2017 10:08:09 PM

I think the best equivalent to PHP's var_dump($foo, $bar) is combine print with vars:

print vars(foo),vars(bar)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon