Skip to content

Instantly share code, notes, and snippets.

@scottnixonjr
Last active March 5, 2021 17:32
Show Gist options
  • Save scottnixonjr/a224a2d94b6f6cb2127ff7e96e2c135e to your computer and use it in GitHub Desktop.
Save scottnixonjr/a224a2d94b6f6cb2127ff7e96e2c135e to your computer and use it in GitHub Desktop.

debugging-python

New in version 3.7: The built-in breakpoint(), when called with defaults, can be used instead of import pdb; pdb.set_trace()

python -m pdb src/index.py

Python's pdb keyboard shortcuts.

Help h

To continue c

List all source code in a file with l,

Display current function or frame with ll

Use p myvarname as a shortcut to print.

Use pp jsonOrYaml-var

whatis myvarname <class 'str'>

Pytest won't respect breakpoint() unless you enable pdb. pytest --pdb

Better Python Repl

Usage

$ ptpython
$ ptipython

PtPython

  • Autocompletion
  • Multiline editing
  • Mouse Support (disabled by default)

iPython

Dynamic object introspection

from collections import Counter
Counter? # docstring
Counter?? # full class

Run shell commands

! pwd
clear
my_path = !pwd

# (provideds autocomplete)
!! script.sh
!! executable.exe

Search modules

boo*?
%psearch boo*?

Magic commands & Macros

%
%% 

Debugging by Default

In [1]: pdb
Automatic pdb calling has been turned ON

In [2]: def home(path):
    ...:     print(path)
    ...:     bad = 1 / 0
    ...:     return bad

In [3]: home()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-9d87ae8f4533> in <module>
----> 1 home()

TypeError: home() missing 1 required positional argument: 'mypath'
> <ipython-input-14-9d87ae8f4533>(1)<module>()
----> 1 home()

ipdb>

Code Performance

In [1]: %timeit 1+1
6.57 ns ± 0.13 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

Auto Reload Tricky and can easily blow up.

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43

Store Magic

In [1]: %load_ext storemagic
In [2]: name = 'John'; age = 21; grades = ['A', 'A', 'B+']
In [3]: %store name age grades
In [4]: exit
# Re-open ipython
In [1]: %load_ext storemagic
In [2]: %store
Stored variables and their in-db values:
age              -> 21
name             -> 'John'
grades           -> ['A', 'A', 'B+']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment