In pdb (or ipdb) we can execute statements and evaluate expressions with the !
or p
commands:
p expression
Evaluate the expression in the current context and print its value.
[!]statement
Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To set a global variable, you can prefix the assignment command with a global command on the same line
So, for example, I can type p reddit.get_subreddits()
while debugging in ipdb and the code will be executed in the current context and I will see the return value.
Is there a way I can debug the execution of such "manually typed" expressions?
Basically I would like to do is s reddit.get_subreddits()
, but that just executes the step
command and ignores the expression.
EDIT: A trivial example
Take this simple function:
import random
def get_value_for_weekday(weekday_index=None):
values = [10, 20, 20, 10, 30, 30, 30]
if not weekday_index:
# If no weekday provided, return the average of all weekdays
return sum(values) / 7
return averages[weekday_index]
if __name__ == '__main__':
while True:
import ipdb; ipdb.set_trace() # enter ipbd for debug
get_value_for_weekday(random.randint(0, 7))
Which is bugged because of the if not weekday_index
(it should check weekday_index is not None
.)
Let's assume I notice I get 10
half the number of times I was expecting. So I added a import ipdb; ipdb.set_trace()
before the call to the function to try and debug the code.
So I'm in the ipdb console and I suddenly get the idea that maybe the problem is when I pass 0 as weekday_index.
I can test my hypothesis directly in ipdb:
ipdb> p get_value_for_weekday(0)
22
Ok, so I realize there's something wrong when weekday_index=0
.
What I would like to do now is debug step by step the call to get_value_for_weekday(0)
, so that I could see that I erranously enter the if block.
Obviously I could exit ipdb, stop the script, change the code to always pass 0, relaunch the script and when I enter ipdb, debug the call with the ipdb step
(s
) command.
But wouldn't it be easier if I could just do s get_value_for_weekday(0)
much the same way I was able to do p get_value_for_weekday(0)
?
Is there a way do something like this?
See Question&Answers more detail:
os