What is a Python equivalent of PHP's var_dump()? [duplicate]
Asked Answered
P

10

494

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?

Preserve answered 21/12, 2008 at 0:43 Comment(4)
I found this looking for the PHP equivalent for pythons repr. Thanks.Recapitulation
the duplicate question @hop mentions (and the highest voted answer) was much more useful for meDesdemona
If you find yourself using this function a lot you may want to consider using a good remote debugger with breakpoints. It maybe hard to understand at first, but it will save you time in the future and once you know how to do it, you will never go back. I know eclipse has a good one and so does Komodo. docs.activestate.com/komodo/8.0/…Gahl
since this thread is closed, see this answer that uses jsonpickle serialization: https://mcmap.net/q/41373/-is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-an-objectAdham
K
331

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.

Kermie answered 21/12, 2008 at 0:59 Comment(5)
what about showing the type of var? like Null/None, String, Object..Clausen
What about pprint() on enumerate objects, permutations, etc.?Lathan
This was helpful. I am a Python noob but what seemed to help my case was using .__dict__, e.g. pprint(object.__dict__).Mchail
object.__dict__ outputs all the properties of the objectBartonbartosch
var_dump in PHP is not just about "displaying a value nicely" 😁Viera
T
349

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

print vars(foo),vars(bar)
Tajuanatak answered 22/5, 2010 at 17:21 Comment(6)
Same here, only thing that worked as I expected (like var_dump)Fyrd
Looks like for vars to work, the variable must have a dictionary info, otherwise you get "TypeError: vars() argument must have __ dict __ attribute".Crosswise
This did it for me - but I like the pprint too. Here is a hybrid: pprint.pprint(vars(foo)).Crackleware
-1, this works only for some types of variables, not all of them. Consider instead pprint or reprKnepper
This answer also works for python pdb debugging with the pp command. e.g. pp vars(my_dict). It should be marked as correct as php var_dump() outputs all the values in the data structure the same as py vars() does.Milissa
Note: For python3 you'll need to use parens like print( vars(foo) )Elizbeth
K
331

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.

Kermie answered 21/12, 2008 at 0:59 Comment(5)
what about showing the type of var? like Null/None, String, Object..Clausen
What about pprint() on enumerate objects, permutations, etc.?Lathan
This was helpful. I am a Python noob but what seemed to help my case was using .__dict__, e.g. pprint(object.__dict__).Mchail
object.__dict__ outputs all the properties of the objectBartonbartosch
var_dump in PHP is not just about "displaying a value nicely" 😁Viera
P
75

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))
Potman answered 22/5, 2012 at 10:58 Comment(1)
This way is much more better of good.Delenadeleon
R
37

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

Usage example:

from var_dump import var_dump

var_dump(1, {"testkey1": "testval1", "testkey2": "testval2".encode("ascii")},
 ["testval"], "test", "test".encode("ascii"), set([1,2,3]))

prints

#0 int(1) 
#1 dict(2) 
    ['testkey1'] => str(8) "testval1"
    ['testkey2'] => object(bytes) (b'testval2')
#2 list(1)
    [0] => str(7) "testval"
#3 str(4) "test"
#4 object(bytes) (b'test')
#5 object(set) ({1, 2, 3})
Rigi answered 30/8, 2013 at 8:0 Comment(3)
Fails on sets - github.com/sha256/python-var-dump/issues/8Contortion
BEST of the best solution, EVER, this utility works so well and does unbelievable formatting of the output. I really strong recommend it!Lithea
@anatolytechtonik that was fixed at 2016-08 ^^Samite
R
29

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

Restoration answered 21/12, 2008 at 3:2 Comment(3)
I think you're thinking of var_export.Grimsby
yep, var_export in php and repr in python are somewhat related - that's if you want an official string representation of some object - you use repr(). In order to have non-official (read human-readable) you can always force conversion to string: str(object), which produces info similar to php's print_r() (used much more ofter for debugging than var_dump).Egression
Please fix the answer, it's incorrect. As mentioned, either you're talking about var_export or describe var_dump() differently.Oldwife
P
17

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)}
Preserve answered 22/12, 2008 at 21:26 Comment(3)
+1, This is the only answer that actually has var_dump's functionality when it encounters objectsBertold
+1 very useful, but it shows an error with "if 'dict' in dir(obj):", I could correct using "if ' instance at ' in str(obj) and obj.__dict__:"Pustulant
this function only take 1 argument, php's var_dump() take *argsSamite
G
9

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
Guillema answered 15/2, 2014 at 0:3 Comment(1)
if type(i) in (list, tuple, dict, set): does not seem to work. When passing an object: TypeError: object of type 'TestPacketDecode' has no len()Aspen
L
2

print

For your own classes, just def a __str__ method

Lupien answered 21/12, 2008 at 0:58 Comment(0)
B
2

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.

Bloodhound answered 22/5, 2012 at 11:38 Comment(0)
C
1

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)
Crutcher answered 18/9, 2009 at 9:8 Comment(1)
if '_' not in str(name).join(str(value)): ^ SyntaxError: invalid syntaxBirkner

© 2022 - 2024 — McMap. All rights reserved.