Python Library Rich: Making Text Beautiful one string at a time!
Tags: python
Published: 2023-06-09 06:16:39

**What is Rich?**
Every programmer strives for sound logic, efficiency, and bug-free code. Unfortunately, this sometimes disconnects the developer and user experience. Rich is a library that helps developers communicate with the different entities in a command line interface (CLI) program by changing the color of words. Text on a screen is just text on a screen, but with style and color text seems to come alive. Rich allows us to bridge the gap and create a more seamless user experience by giving us tools to create visually appealing and intuitive CLI text.

In this blog, we will cover:

- How do you install Rich?
- How do you use Rich to format text?
- Using Rich to create custom styles and themes.
- Rich in practice.
- Additional resources.

**How do you install Rich?**
Rich can be installed with pip or any other package manager which supports the Python Package Index (PyPI), simply run the command to install ‘rich’ through your package manager as seen below using pip.

`pip install rich`

**How do you use Rich to format text? **
The Rich library has two main ways of begin used:
First, you can import the ‘print’ method from Rich (this will overwrite the basic ‘print’ method for Python with the version implemented through the Rich library).
Alternatively, you can import the ‘Console’ object from ‘rich.console’ as seen below. We will be using this method throughout the blog.

`from rich.console import Console`

In rich  there are a variety of ways to modify your text, these include style, color, links and code.

**Styles with Rich:**
There are several basic formatting options through Rich, these are **bolded**, _italicized_ and <u>underlined</u>. Applying a format can be done by adding [square] brackets with the formatting options before the text, and closing [/square] brackets with a forward slash and formatting options in a closing tag after the text. Multiple options can be added to a tag by adding a space between each option, an example of this can be seen below.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgvf1i6540w5cy0v5b4w.png)

The code above gives the following output when run in the terminal. You can do this by importing Rich, adding the above lines to your Python file, and running that file in your terminal using a Python interpreter.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x84apapfq6frb8xwy6e.png)

**Color with Rich:**
Coloring is done in a similar fashion to formatting with the same style of tags. To select a color there are four main options, you can use the name of a color corresponding to one of the 256 standard colors in Rich, you can use the corresponding number for a color (specified in the [Rich documentation](https://rich.readthedocs.io/en/stable/introduction.html)), a hex code, or an rgb value.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnaz44xjptpg6c0q1pqi.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjmmktvo9ym8ayl3xhlf.png)
Above we use all four methods to produce the color steel_blue, although it should be noted that using rgb and hex values will allow for a wider range of colors (in terminal environments that will allow it).


**Links with Rich:**
Aside from adding a URL to the first part of the tag, links are very similar to the previous two options. It is important to remember that the text between the tags is the text that will lead to the link, this includes any whitespace.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3t6g7xqx3hti0cocxzn.png)

In the above code you can see that we set the link equal to ‘https://www.google.com’, and below you can see the terminal output, which when clicked will lead to the set link.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ugt0cwm9bv69wtx7dq6q.png)

**Code with Rich:**
To style code in Rich automatically one can use the Syntax module in Rich. To start you must import ‘Syntax’ from ‘rich.syntax’ and create a Syntax object as seen below. The Syntax object in Rich can read a file and automatically detect which language it is written in, it then applies the appropriate styling for the read file and the Syntax object can be printed. The entire aforementioned process can be seen below.

`from rich.syntax import Syntax

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6f9g3liqnqdyvklsx5a.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8m1ajc57paohv5onoiq3.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/44tqox21hvrrktl5pxqi.png)

**Using Rich to create custom styles and themes:**
In rich a style is a collection of tags that can be applied to entire pieces of text. Previously we have been including all of our tags inline, this is like trying to paint by squeezing out the color of paint you want for a section, cleaning your brush once you are done, and then squeezing out more paint for the next section. This is obviously inefficient and time-consuming as you will likely need the same color for more than one part of your painting, styles and themes allow you to make a proverbial palette in which you can dip your brush whenever you need a particular color. The ‘Theme’ class in rich allows for much quicker access and use of common colors/styles.  To start, you need to first import both the rich ‘Console’ and ‘Theme’ as you can see in the code block below.


`from rich.console import Console`
`from rich.theme import Theme`


Once imported, you are ready to begin constructing your metaphorical color palette.  The syntax for this is quite simple. First, you must create an instance variable (in this case, we have named it ‘custom_theme’) using the ‘Theme()’ constructor method. The ‘Theme()’ constructor takes a dictionary of style names and corresponding tags for those styles. For our particular example, we have made all of our styles colors, however, it is worth pointing out that these styles can also include **bold**, _italic_, <u>underline</u>, or any other style mentioned in the documentation [here](https://rich.readthedocs.io/en/stable/style.html). To pick up your color palette and use it you will have to set the theme of your ‘Console’ object to custom_theme. This can be done on initialization,


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4jkhfunux5krqlcdyeg.png)

To paint with your pallet, you can now set the style of your ‘console.print()’ commands to the keys that you declared in your ‘Theme’ dictionary. You can see below that we call print with a string, and rather than using inline tags we declare a style. This style can be a set of tags, but since we have prepared our proverbial pallet we can know access the colors by the keys as mentioned earlier.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fun202q4oyeb9hixlnd5.png)

Now below we can see our beautiful painting.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8c9vdkvs10710nptk2a.png)

**Rich in practice:**
My classmates and I are currently working on a CLI game to teach people about Git. You have already seen the theme for this project in the previous section, this theme is put in use in our game with color being used to help the player differentiate loot, good and bad actions or when they are being asked to do something. This helps to make the game more intuitive and immersive, when a player gets a shiny object and the message is highlighted in gold, then the player feels an achievement and will associate the color with getting something good. Similarly, when the player performs well in combat the green success message sends a ping to their brain that they have succeeded. Colors should not be picked at random when creating UI, as people often have certain associations with different colors. An example of people having preconceptions of colors, imagine a green exit button… it just feels wrong somehow does it not?

We start our game with a friendly cyan color, and use blue for neutral messages. We also change the color of options to make it clear that the player knows what they can choose to do next.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hneyw6pgkxgmwpz8nen.png)

Below you can see an example of text prompting the player character to move, this text is in purple to signify that it is a character action. The player options are presented in the neutral color of blue so as to not spoil the contents of the game for the player, after all, what fun is a game where you always know exactly what is coming next?


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmesvvem5ftb13xob2it.png)

**Additional resources:**
There are a lot of features in Rich which this Blog doesn’t have the time to cover, but if you are interested in learning more about Rich and how to format your text then you can dive into the documentation. Of particular note for formatting text is the ‘Table’ class which can be found at the link [here](https://rich.readthedocs.io/en/stable/tables.html).

Another very useful class in Rich is the ‘Layout’ class found [here](https://rich.readthedocs.io/en/stable/layout.html), which can let you split the terminal into several boxes and display text within them.

To conclude, check out the [Rich documentation](https://rich.readthedocs.io/en/stable/introduction.html) overall if you really want to get a ‘rich’ understanding (pun intended), and thanks for reading!