Improve your Django experience with IPython2021-02-21
IPython is an improved Python shell for interactive use. It has many great features such as syntax highlighting, autocomplete, and powerful “magic commands”. I love it, use it on every project, and use the IPython prompt for examples on my blog.
IPython has too much goodness to cover here. Check out its tutorial for an introduction.
To use IPython with Django, simply install it:
(Or add to your project’s requirements file.)
shell will automatically use IPython:
In this example, I typed
Server then pressed “Tab” and IPython opened a drop-down of possible names to import.
IPython also comes with an improved version of Python’s
pdb debugger, with colorization and other features.
Inside the IPython shell, if you code raises an exception, you can open the IPython debugger with the
%debug magic command:
In this session, I first added the
divide() function and then ran it, and it crashed.
In  I typed
%debug, which started the IPython debugger at the line of code that raised the
This is the
post_mortem() pdb method.
THe debugger showed the function with an arrow pointing at the line of code that raised the exception.
I then checked the values of the
Using pdb, and by extension ipdb, is a skill in itself. For more information, check out:
- Anthony Sottile’s introductory video
- Real Python’s introductory blog post
- The pdb documentation “Debugger Commands” section
Using IPython’s debugger outside of IPython
You can use IPython’s debugger outside of its shell by installing the wrapper package
Now you can start the debugger similar to
But, since Python 3.7, the new
breakpoint() built-in is the best way to start a debugger.
This allows you to use an alternative debugger with the same syntax, maybe even with per-project customization.
pdb, but we can make it use
ipdb by setting the
PYTHONBREAKPOINT environment variable.
You can do this at the top of your
Now if you need to start the debugger at some point in your code, you can add a call to
For example in a view:
Using IPython’s debugger in tests
Django’s test framework has a
--pdb flag to open a debugger on test failure.
It will automatically use
ipdb once you’ve installed it.
pytest has a similar
You can configure
--pdb to use the IPython debugger by setting the
This is most conveniently done in the
addopts setting in your
pytest.ini (or other configuration file):
May your adventures never cease,
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
© 2021 All rights reserved.