Personalize your python prompts

The >>> we see when the Python interactive shell starts, is called the Prompt String. Usually, the prompt string suggests that the interactive shell is now ready to take new commands.

Python has 2 prompt strings, one primary >>> and one secondary ... which we usually see when an execution unit (statement) spans multiline, for example: while defining a function

Personalizing the prompt strings

The prompt strings are defined in the sys module as ps1 and ps2 and just like any other attribute we can change the values of sys.ps1 and sys.ps2 and the changes take effect immediately and as a result, the prompt we see in the shell changes to the new value.

From the example above we see that changing the value of sys.ps1 to ::: changes the prompt to :::.

As the interactive shell runs in a terminal, we can color and format it using bash color format as shown below

The code snippet above makes our primary prompt string yellow and secondary prompt string blue. Here's how it looks

Python colored prompt

Dynamic prompt strings

The documentation states that if we assign a non-string object to ps1 or ps2 then Python prompts by calling str() on the object every time a prompt is shown. Now we create some stateful and dynamic prompt by defining a class and overriding the __str__ method.

Below we implement IPython like prompt where execution statement number is stored in member line of the class and is incremented every time the primary prompt renders.

The above code snippet makes prompt look like this

ipython prompt

Setting new prompt strings every time the shell starts

We would not want to run this code snippet every time we start the shell and hence we use an environment variable PYTHONSTARTUP which holds the path of a readable file and is executed before the first prompt is displayed in interactive mode.

So we dump the code snippet in a file, say ipython.py and export PYTHONSTARTUP as

Now every time, we start our Python interactive shell, it will execute the file ipython.py and set the required prompt strings.

Conclusion

Combining everything mentioned above I have created a utility called py-prompts. Here is a glimpse of the themes that the package holds.

Pretty Python Prompts GIF

I hope you found this piece interesting. Python being an exhaustively extensible language made it super-easy for us to change the prompt strings and be creative with it. If you have a theme idea or have already personalized your prompt, share it with me @arpit_bhayani, I will be thrilled to learn more about it.

Other articles that you might like:


If you find this helpful, share this with your peers and give me a shout out @arpit_bhayani