Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you see the return value from a function in the Python debugger, without an intermediate?

PDB (and other Python debuggers) have a simple way of viewing the value of any current variable, just by typing it in. However, sometimes I work with libraries that don't store their return values in intermediate variables.

Here's an example function:

def do_stuff(*args, **kwds):
     return f(*args, **kwds)

After I return from f, how do I see the return value? I could rewrite libraries after I download them to have an intermediate:

def do_stuff(*args, **kwds):
     r = f(*args, **kwds)
     return r

but it seems like there should be a better way.

like image 651
Chris Avatar asked Jun 05 '12 17:06

Chris


People also ask

How do you check if a function has a return value in Python?

A function by definition always returns something. Even if you don't specify it, there is an implicit return None at the end of a python function. You can check for a "return" with the inspect module.

How do you get the value returned from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

What is the default return value of a function without a return statement in Python?

If the return statement is without any expression, then the special value None is returned.

How do you find the return value?

There are 2 places where we can see the method return value: In the Debugger Immediate window, using the $ReturnValue keyword. To open the Immediate window while debugging, choose Debug -> Windows -> Immediate (or press keyboard shortcut: Ctrl + Alt + I). In the Debugger Autos window.


2 Answers

You can look into a hidden __return__ local variable.

If I would forget it's exact name, I explore it by this:

(Pdb) sorted(locals().keys())
['__return__', 'xyz', ...]

EDIT: Related later answer with example of debugging with __return__

like image 50
hynekcer Avatar answered Sep 29 '22 13:09

hynekcer


In pdb, when the function returns a ->'value' is added at the end of the line with the representation of the returned value.

For example:

(Pdb) s
--Return--
> test.py(12)do_stuff()->'f'
-> return result
(Pdb) q

means do_stuff() returned 'f'

like image 38
KurzedMetal Avatar answered Sep 29 '22 12:09

KurzedMetal