Today I learned how to customise the Python REPL on start-up.
Customising the Python REPL on start-up allows you to run custom code whenever you open the Python REPL. Typically, people use this to import modules they use commonly or define functions that they use a lot.
To customise the Python REPL, you need two things:
.pythonrcin which you write the code you want to run when the REPL starts.
PYTHONSTARTUPto point to the file.
Then, when the REPL starts, it will look at the environment variable
PYTHONSTARTUP and if it is set to something, it will run the Python code in that file.
.pythonrc file is very simple and looks like this:
from functools import partial try: from rich import inspect, pretty, print, traceback help = partial(inspect, help=True) pretty.install() traceback.install() print("rich setup concluded.") except ImportError: pass
It uses the module
rich to override the built-ins
That way, whenever I use
rich, which I am really fond of.
Additionally, it uses
rich.pretty to install automatic pretty-printing in the REPL and
rich.traceback to pretty print exception tracebacks.
If you want to have the same
.pythonrc file, just be sure to install
python -m pip install rich.
To set your environment variable
PYTHONSTARTUP to point to your
.pythonrc file, you can run the command
set PYTHONSTARTUP=C:\path\to\your\file\.pythonrc # Windows
export PYTHONSTARTUP=/path/to/your/file/.pythonrc # MacOS / Linux
To make sure everything is working, add a
print("hello world") to your file
.pythonrc and open the shell.
You should see your greeting.
If you want this configuration to be set permanently, what you can do is figure out the file that your shell uses for start-up customisation.
For example, when my shell starts, it runs the commands found in the file
So, if I add the line
export PYTHONSTARTUP=/path/to/your/file/.pythonrc to my file
python will always know where to find the file
I first heard of the
.pythonrc file when reading Adam Johnson's “Boost Your Git DX”1, where Adam suggests that configuration files like these (as long as they don't have sensitive data, like credentials) could be kept in a GitHub repository.
Then, you just create a symlink from the typical location
~/.pythonrc to the versioned file in your repository.
This way, when you change computers, you have all your configurations ready to be cloned from the repo and they're easier to setup on your new machine.
That's it for now! Stay tuned and I'll see you around!
If you buy this book, I may get an affiliate commission because I referred you to it, but this comes at no extra cost to you. ↩
If you enjoyed this blog article, you will love the mathspp insider 🐍🚀 newsletter! Join +16.000 others who are taking their Python 🐍 skills to the next level! 🚀