Customising your Python REPL
4 August 2024

This blog post will show you how to customise your Python REPL by running a Python file before the interactive prompt is loaded. This is achieved using the PYTHONSTARTUP environment variable.

Initial set up.

By way of an initial example, you may wish to always have the pprint function available when the REPL loads.

To achieve this we must first have a python file that will be run before the REPL loads.

Create a file:

touch .pythonstartup.py

Populate file with code to import pprint:

# import pprint
from pprint import pprint

And finally, set the PYTHONSTARTUP environment variable to point at our Python file:

export PYTHONSTARTUP=~/.pythonstartup.py

To test if this is working, launch a Python REPL and check the function is available.

>>> pprint
<function pprint at 0x7f4c0e9ebb00>

Alternative shell

Alternative shells are available such as IPython or Ptpython. While these can be launched via their own commands you could also use your PYTHONSTARTUP script to try to launch them as your default shell.

We'll use Ptpython as an example. The .pythonstartup.py file becomes:

from pprint import pprint

import sys
try:
    from ptpython.repl import embed
except ImportError:
    print("ptpython is not available: falling back to standard prompt")
else:
    sys.exit(embed(globals(), locals()))

By passing globals() and locals() to embed() this allows the imported pprint() function to be available in the new shell.

If you were using IPython this could be achieved by using start_ipython() and using the user_ns parameter to initalise the IPython namespace.

Django shell

The django-admin CLI has a shell command.

This has an --interface option which can be used to launch the shell with different shells (ipython, bpython, python).

Using the script above the PYTHONSTARTUP the Ptpython shell will be launched by default. If you wished to instead use the default Python shell this could be achieved by specifying the Python shell and using the --no-startup option:

django-admin shell --interface python --no-startup

Conclusion

Using a custom PYTHONSTARTUP script can be used to import frequently used functions so they are always available and allow use of your favourite Python shell with Django even if it doesn't have a built-in option.