- When debugging in PHP, we frequently find it useful to simply stick a var_dump() in our 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?
When debugging in PHP, we frequently find it useful to simply stick a var_dump() in our code to show me what a variable is, what its value is, and the same for anything that it contains.
- To display a value, you can use the pprint module. The easiest way to dump all variables with it is to do
- 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.
[pastacode lang=”python” manual=”def%20dump(obj)%3A%0A%20%20”’return%20a%20printable%20representation%20of%20an%20object%20for%20debugging”’%0A%20%20newobj%3Dobj%0A%20%20if%20’__dict__’%20in%20dir(obj)%3A%0A%20%20%20%20newobj%3Dobj.__dict__%0A%20%20%20%20if%20’%20object%20at%20’%20in%20str(obj)%20and%20not%20newobj.has_key(‘__type__’)%3A%0A%20%20%20%20%20%20newobj%5B’__type__’%5D%3Dstr(obj)%0A%20%20%20%20for%20attr%20in%20newobj%3A%0A%20%20%20%20%20%20newobj%5Battr%5D%3Ddump(newobj%5Battr%5D)%0A%20%20return%20newobj%0A” message=”Python code” highlight=”” provider=”manual”/]
- Here is the usage
and the results
[pastacode lang=”python” manual=”%7B%0A’__type__’%3A%20’%3C__main__.stdClass%20object%20at%200x2b126000b890%3E’%2C%0A%20’dict’%3A%20%7B’a’%3A%201%2C%20’c’%3A%203%2C%20’b’%3A%202%2C%20’more’%3A%20%7B’y’%3A%2025%2C%20’z’%3A%2026%7D%7D%2C%0A%20’int’%3A%201%2C%0A%20’list’%3A%20%5B1%2C%202%2C%203%2C%20’a’%2C%20’b’%2C%20’c’%2C%20%5B1%2C%202%2C%203%2C%204%5D%5D%2C%0A%20’subObj’%3A%20%7B’__type__’%3A%20’%3C__main__.stdClass%20object%20at%200x2b126000b8d0%3E’%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20’value’%3A%20’foobar’%7D%2C%0A%20’tup’%3A%20(1%2C%202%2C%203%2C%204)%0A%7D%0A” message=”Python code” highlight=”” provider=”manual”/] [ad type=”banner”]- You can simply install it using pip:
- Here we use self-written Printer class, but dir() is also good for outputting the instance fields/values.
class Printer:
[pastacode lang=”python” manual=”%20%20%20%20%20%20%20def%20__init__%20(self%2C%20PrintableClass)%3A%0A%20%20%20%20%20%20%20%20%20%20%20for%20name%20in%20dir(PrintableClass)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20value%20%3D%20getattr(PrintableClass%2Cname)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20%20’_’%20not%20in%20str(name).join(str(value))%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print%20’%20%20.%25s%3A%20%25r’%20%25%20(name%2C%20value)%0A” message=”Python code” highlight=”” provider=”manual”/]- The sample of usage:
- In PHP’s var_dump() is pprint() with the getmembers() function in the built-in inspect module:
- The best equivalent to PHP’s var_dump($foo, $bar) is combine print with vars:
easy explanation
good one
useful
Great
Super