The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 What Is A Python Equivalent Of Php'S Var_dump()?
00:17 Accepted Answer Score 332
00:38 Answer 2 Score 30
01:01 Answer 3 Score 350
01:15 Answer 4 Score 76
01:26 Thank you

--

Full question
https://stackoverflow.com/questions/3839...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#php #python #debugging

#avk47



ANSWER 1

Score 350


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

print vars(foo),vars(bar)



ACCEPTED ANSWER

Score 332


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.




ANSWER 3

Score 76


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))



ANSWER 4

Score 30


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() [...]"