print_r() or var_dump()

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jul 15 02:19:57 CEST 2004


Thomas Lindgaard wrote:

> Now I have a typing problem - one of my variables is reported as having a
> different type from what I expect it to. To the best of my knowledge it
> should be a string, but it turns out to be 'instance' (of Token).

> Is there a way for me to print out what is stored in my variable 

I suppose you mean what my name is associated with.  Python doesn't
really have variables with storage as you imagine them.  This
misconception is often at the root of bugs.

 > - kinda like in PHP where var_dump($variable) dumps the variable in a
 > human readable form:
> 
>   <?php
>     class C { var $str = 'this is a string'; }
>     $instance = new C();
>     var_dump($instance);
>   ?>
> 
> outputs:
>   
>   object(c)(1) {
>     ["str"]=>
>     string(16) "this is a string"
>   }

If I understand this correctly, you might want:

def info(v):
     return '%s = %r %s' % (v, v, type(v))

and you can:
     print info(v)

Or, in many cases:

for name, val in vars(obj):
     print '  .%s: %r' % (name, val)


-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list