print_r() or var_dump()

T

Thomas Lindgaard

Hello

I am writing my first (real) Python script (a multithreaded web crawler).
It is an extension of the source code found here:

http://starship.python.net/crew/aahz/OSCON2001/ThreadPoolSpider.py

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 - 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"
}

Additionally, I have used curses for output - but combined with the
occasional uncaught exception, my nice interface completely breaks down
sometimes. How do I handle exceptions best (and how do I find out how to
get the error message)? One of my try...except blocks looks like:

try:
...
except socket.gaierror, (error, string):
...

Do exceptions _always_ return error and string or does this change with
the type of exception - and if so, then how do I find out what to expect
from the exception?

Hmm... I better stop now...
 
S

Scott David Daniels

Thomas said:
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
salsusa

Latest Threads

Top