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.
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
python code
import pprint
pprint.pprint(globals()) pprint.pprint(locals())
[ad type=”banner”]
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.
Python code
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
Python code
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))
Here we use self-written Printer class, but dir() is also good for outputting the instance fields/values.
class Printer:
Python code
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:
Python code
Printer(MyClass)
In PHP’s var_dump() is pprint() with the getmembers() function in the built-in inspect module:
python code
from inspect import getmembers from pprint import pprint pprint(getmembers(yourObj))
The best equivalent to PHP’s var_dump($foo, $bar) is combine print with vars:
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.
easy explanation
good one
useful
Great
Super