Bring your custom toolkit to REPL sessions
Batteries included is a blog series about the Python Standard Library. Each day, I share insights, ideas and examples for different parts of the library. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.
Python’s REPL (read-eval-print loop) is one of my favourite tools. Whether it is to run one-off scripts, developing new functionality step-by-step or debugging issues, I almost always have a session open.
On default, it provides the same functionality that the Python standard library provides with a few extra interactive bits on top.
What really makes it powerful though is that you can bring in your own code pre-loaded by pointing the PYTHONSTARTUP environment variable to a Python file. Whatever file it’s pointed at will be loaded before the interactive session starts so you import all your favourite standard library functions and add custom helper functions all ready to go.
You can keep one general file ready to go for any of your sessions and then have another, project-specific one that you point to whenever you’re working on that project.
Let’s say you have a file
~/startup.py
with
print('Startup file loaded')
and you run Python with
PYTHONSTARTUP
pointed to that file,
you’ll get:
$ PYTHONSTARTUP="/Users/juhis/startup.py" python
Python 3.12.1 (main, Jan 10 2024, 20:52:06) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Startup file loaded
>>>
Now, you can do whatever you want in your
startup.py
file: import the libraries you usually need, set up helper functions and
customize the experience in a way that helps you get running faster so you can
focus on the important bits.
You can even have different files for different use cases and load them as needed.
To automatically load the startup file, put the environment variable into your shell profile file and you’ll always have access to it.