pdb is a fully featured python shell, so you can execute arbitrary commands.

locals() and globals() will display all the variables in scope with their values.

You can use dir() if you're not interested in the values.

When you declare a variable in Python, it's put into locals or globals as appropriate, and there's no way to distinguish a variable you defined and something that's in your scope for another reason.

When you use dir(), it's likely that the variables you're interested in are at the beginning or end of that list. If you want to get the key, value pairs

Filtering locals() might look something like:

>>> x = 10
>>> y = 20
>>> {k: v for k,v in locals().iteritems() if '__' not in k and 'pdb' not in k}
{'y': 20, 'x': 10}

If your locals() is a real mess, you'll need something a little more heavy handed. You can put the following function in a module on your pythonpath and import it during your debugging session.

def debug_nice(locals_dict, keys=[]):
    globals()['types'] = `__import__`('types')
    exclude_keys = ['copyright', 'credits', 'False', 
                    'True', 'None', 'Ellipsis', 'quit']
    exclude_valuetypes = [types.BuiltinFunctionType,
                          types.BuiltinMethodType,
                          types.ModuleType,
                          types.TypeType,
                          types.FunctionType]
    return {k: v for k,v in locals_dict.iteritems() if not
               (k in keys or
                k in exclude_keys or
                type(v) in exclude_valuetypes) and
               k[0] != '_'}

I've added an example session on pastebin

There are a couple of cases this misses. And you might want to extend it to allow you to pass in types too. But it should let you filter most everything but the variables you defined.

dir()

If you just want the last 20 values so you get output like >>> p var1 var2 ... varn would give you, then you're better off slicing dir() like dir()[-20:], but you won't easily see the relationship between the variables and values. eg: "Did I declare foo before or after bar?"

If you want to see that relationship, you can try something like this, which assumes that your variables are at the end of dir(). You can slice differently if they're at the beginning. This won't work well if your variables aren't contiguous.

>>> zip(dir(), [eval(var) for var in dir()])[-4:]
[('a', 10), ('var', 'var'), ('x', 30), ('y', 50)]
Answer from munk on Stack Overflow
Top answer
1 of 2
132

pdb is a fully featured python shell, so you can execute arbitrary commands.

locals() and globals() will display all the variables in scope with their values.

You can use dir() if you're not interested in the values.

When you declare a variable in Python, it's put into locals or globals as appropriate, and there's no way to distinguish a variable you defined and something that's in your scope for another reason.

When you use dir(), it's likely that the variables you're interested in are at the beginning or end of that list. If you want to get the key, value pairs

Filtering locals() might look something like:

>>> x = 10
>>> y = 20
>>> {k: v for k,v in locals().iteritems() if '__' not in k and 'pdb' not in k}
{'y': 20, 'x': 10}

If your locals() is a real mess, you'll need something a little more heavy handed. You can put the following function in a module on your pythonpath and import it during your debugging session.

def debug_nice(locals_dict, keys=[]):
    globals()['types'] = `__import__`('types')
    exclude_keys = ['copyright', 'credits', 'False', 
                    'True', 'None', 'Ellipsis', 'quit']
    exclude_valuetypes = [types.BuiltinFunctionType,
                          types.BuiltinMethodType,
                          types.ModuleType,
                          types.TypeType,
                          types.FunctionType]
    return {k: v for k,v in locals_dict.iteritems() if not
               (k in keys or
                k in exclude_keys or
                type(v) in exclude_valuetypes) and
               k[0] != '_'}

I've added an example session on pastebin

There are a couple of cases this misses. And you might want to extend it to allow you to pass in types too. But it should let you filter most everything but the variables you defined.

dir()

If you just want the last 20 values so you get output like >>> p var1 var2 ... varn would give you, then you're better off slicing dir() like dir()[-20:], but you won't easily see the relationship between the variables and values. eg: "Did I declare foo before or after bar?"

If you want to see that relationship, you can try something like this, which assumes that your variables are at the end of dir(). You can slice differently if they're at the beginning. This won't work well if your variables aren't contiguous.

>>> zip(dir(), [eval(var) for var in dir()])[-4:]
[('a', 10), ('var', 'var'), ('x', 30), ('y', 50)]
2 of 2
6

As given in this list for multiple languages:

a = 1
b = 1
n = 'value'
#dir() == ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b', 'n']
for var in dir()[4:]:
    value_of_var = eval(var)
    print(value_of_var)

Output:

1
1
'value'

Labelling each one is as simple as printing var + " equals " + eval(var).

You state your "ideal output" is exactly the result as typing p a, b, ... , n, ...:

vars = []
for var in dir()[4:-1]
    vars.append(var)
print(tuple(vars))

Output looks like:

(1, 1, 'value')
๐ŸŒ
W3Resource
w3resource.com โ€บ python-interview โ€บ how-can-you-inspect-variables-values-during-debugging-using-pdb-in-python.php
Inspecting Variable Values with 'pdb' in Python Debugging
August 12, 2023 - Learn how to inspect and display variable values during Python debugging using 'pdb'. Explore commands like p (print), pp (pretty print), a (args), w (where), and l (list) to efficiently analyze variables and troubleshoot code.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ pdb.html
pdb โ€” The Python Debugger
The debugger is extensible โ€“ it is actually defined as the class Pdb. This is currently undocumented but easily understood by reading the source. The extension interface uses the modules bdb and cmd. ... Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal. ... Standard interface to extract, format and print stack traces of Python programs.
๐ŸŒ
Real Python
realpython.com โ€บ python-debugging-pdb
Python Debugging With Pdb โ€“ Real Python
May 19, 2023 - Enter p variable_name at the (Pdb) prompt to print its value. Letโ€™s look at the example. Hereโ€™s the example1.py source: ... If youโ€™re having trouble getting the examples or your own code to run from the command line, read How Do I Make ...
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Use p variable to print in debugger - Python Help - Discussions on Python.org
April 4, 2024 - Can we use โ€œp variableโ€ to print a variable in the debugger? So we donโ€™t have to type out โ€œprint(myvar)โ€. Is that possible?
๐ŸŒ
Supersqa
supersqa.com โ€บ python-debugger-pdb
Python Debugger PDB Tutorial
My go-to is "pp" because it prints in a 'pretty' format, which stands for 'pretty print'. This command is particularly useful when dealing with complex data structures as it makes the output more readable and easier to understand. ... admas@/.../python-debugger-pdb : python3 main.py > /Users/admas/Demos/python-debugger-pdb/main.py(6)main() -> processed_data = process_data(data) (Pdb) print(data) {'name': 'Jane Doe', 'age': 28, 'city': 'New York', 'country': 'USA', 'enrolled': True} (Pdb) p data {'name': 'Jane Doe', 'age': 28, 'city': 'New York', 'country': 'USA', 'enrolled': True} (Pdb)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 79692233 โ€บ how-to-automatically-print-a-variable-in-pdb
python - How to automatically print a variable in pdb? - Stack Overflow
... @jsotola It's a self-answered question, which is encouraged on Stack Overflow if it helps others: stackoverflow.com/help/self-answer. ... Yes, It can be done using display command.
Find elsewhere
๐ŸŒ
CSDN
devpress.csdn.net โ€บ python โ€บ 62fd0d377e66823466191448.html
How to print all variables values when debugging Python with pdb, without specifying each variable?_python_Mangs-Python
August 17, 2022 - Answer a question I'm debugging my Python scripts using pdb and the manual says I can use p variables command to print the values of the specified variables at a certain point. But what if I had lots Mangs Python
๐ŸŒ
Scaler
scaler.com โ€บ topics โ€บ pdb-python
PDB Python Debugger| Scaler Topics
December 13, 2022 - Pdb's main benefit is that it only ... ... When using the print order p, you are sending Python an expression to evaluate. If you supply a variable name, PDB will print its current value....
๐ŸŒ
Medium
medium.com โ€บ python-features โ€บ debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7
Debugging in Python โ€” A cakewalk with pdb | by Rachit Tayal | Python Features | Medium
September 9, 2019 - Now to execute the next line we can either hit n again. Or just typing the enter key will repeat the previous command issued. ... We can print local variables, program state using the p command followed by variable name.
๐ŸŒ
DEV Community
dev.to โ€บ koladev โ€บ efficient-debugging-in-python-a-guide-to-using-pdb-over-print-2nj1
Efficient Debugging in Python: A Guide to Using pdb Over print - DEV Community
July 25, 2024 - This article is about why debugging in Python using the built-in debugger called pdb is better than using print statements. We will learn how to use pdb to manipulate a running program and inspect some errors. If you are interested in more content covering topics like this, subscribe to my newsletter for regular updates on software programming, architecture, and tech-related insights. Debugging in Python is straightforward. I mean, I have an error, right? A variable with the wrong format?
๐ŸŒ
Calmops
calmops.com โ€บ programming โ€บ python โ€บ python-debugging-pdb-print-statements
Python Debugging: Mastering pdb and Print Statements - Calmops
December 16, 2025 - # Problem 1: Cluttered output def complex_function(data): print(f"Start: {data}") for item in data: print(f"Processing: {item}") result = item * 2 print(f"Result: {result}") print("Done") # Output is hard to follow # Problem 2: Can't inspect state at specific points def buggy_function(x): y = x * 2 # Can't easily check what y is without adding print z = y + 10 return z # Problem 3: Requires code changes # You must modify your code to add prints, then remove them later # Problem 4: Can't easily change debugging level # You have to manually add/remove print statements ยท The Python Debugger (pdb) lets you pause execution and inspect your code interactively.
Top answer
1 of 6
46

data breakpoints with pdb

...much like you can watch a memory address in gdb...

  • GDB uses data breakpoints, this is made easy with hardware support (hardware watchpoints), this typically involves marking the memory pages read-only which then trips an exception handler on memory access. When hardware watchpoints are not available it uses software watchpoints, these are only useful in single threads and are much slower.
  • PDB does not support data breakpoints, so the short answer is NO, you cannot do it with PDB out of the box.

printing variables when hitting breakpoints in pdb

For watching a variable when you are hitting a breakpoint, you can use the commands command. E.g. printing some_variable when hitting breakpoint #1 (canonical example from pdb doc).

(Pdb) commands 1
(com) print(some_variable)
(com) end
(Pdb)

Additionally, you can use the condition command to ensure the breakpoint is only hit whenever the variable takes a certain value.

eg:

(Pdb) condition 1 some_variable==some_value

other solutions

You can use tracing / profiling functions to examine things step by step using sys.settrace and checking out the opcodes being executed.

Here is some code to get you started:

import sys
import dis


def tracefn(frame, event, arg):
    if event == 'call':
        print("## CALL", frame)
        frame.f_trace_opcodes = True
    elif event == 'opcode':
        opcode = frame.f_code.co_code[frame.f_lasti]
        opname = dis.opname[opcode]
        print("## OPCODE", opname)
    return tracefn


watchme = 123

def foo():
    global watchme
    watchme = 122

sys.settrace(tracefn)

foo()

You will probably need to spy on all the STORE_* opcodes. https://docs.python.org/3/library/dis.html

2 of 6
33

For Python 3:

you can use display functionality of pdb

Once you hit the breakpoint just type

ipdb> display expression

example:

ipdb> display instance
display instance: <AppUser: dmitry4>
ipdb> display instance.id
display instance.id: 9
ipdb> display instance.university
display instance.university: <University: @domain.com>

ipdb> display

Currently displaying:
instance.university: <University: @domain.com>
instance.id: 9
instance: <AppUser: dmitry4>
ipdb> 

as you can see, each time you type display - it will print all of your watches (expressions). You can use builtin function undisplay to remove certain watch.

You can also use pp expression to prettyprint the expression (very useful)

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ debugging-python-applications-with-the-pdb-module
Debugging Python Applications with the PDB Module
August 24, 2023 - To do that, let's clear all the previous breakpoints and declare another breakpoint through the PDB prompt: ... After that, type "y" and hit "Enter". You should see an output like this appear: Deleted breakpoint 2 at /Users/junaid/Desktop/calc.py:6 Deleted breakpoint 3 at /Users/junaid/Desktop/calc.py:8 ... What we wish to achieve is that the code should run up until the point that the value of the num variable is greater than 10. So basically, the program should pause before the number "20" gets printed.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ debugging-in-python-with-pdb
Debugging in Python with Pdb - GeeksforGeeks
February 28, 2022 - We run this on Python idle terminal (you can use any ide terminal to run). Let's begin with a simple example consisting of some lines of code. ... # importing pdb import pdb # make a simple function to debug def fxn(n): for i in range(n): print("Hello!