Home TechnologyCoding Getting rich with Python

Getting rich with Python

How to Use the Rich Library with Python

by Ivan

I recently learned about a powerful library for Python called Rich. In this story I will share how to use it.

Rich Python Library

Rich is a library that can be imported in Python for writing (beautiful) rich text (with color and style) to the terminal. With it, we can show advanced content — for example, tables, markdown, and syntax-highlighted code.

Using Rich can help understanding code due to its markup styles, its table formatting, etc. Moreover, it makes the output on the terminal look cleaner, and, let’s face it, more beautiful.

How to Install Rich

You can install Rich with pip as:

pip install Rich

To know what all Rich can do, you can type the following command in the terminal:

python -m rich
rich · GitHub Topics · GitHub

That is quite a lovely visual representation about the things you can do with Rich. Below we will use a few of these.

How to Rich print in Python

Rich can highlight the output according to the datatype. To use print you will need to import this. The Rich print function uses the same arguments as Python’s built in print .

Nevertheless, I will import print from the rich library as rprint.

from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)

Output:

Screenshot-2022-02-06-104950

Do you see how the different data types are highlighted with different colors? This can help us a lot while debugging.

How to Rich inspect in Python

If you use the built-in help function for viewing the documentation of a library, you’ll see a boring output.

import rich

print(help(rich))

Output:

Screenshot-2022-02-06-110118

Rich has an inspect() function which can generate a report on any Python object. It is a fantastic debug aid, and a good example of the output that Rich can generate.

from rich import inspect
import rich

inspect(rich)

Output:

Screenshot-2022-02-06-105936

How to style your console with Rich

For complete control over terminal formatting, Rich offers a Console class.

Let’s write a function to merge Python dictionaries.

from rich.console import Console

console = Console()


def merge_dict(dict_one, dict_two):
    merged_dict = dict_one | dict_two
    console.log(merged_dict, log_locals=True)


merge_dict({'id': 1}, {'name': 'Ashutosh'})

Output:

Screenshot-2022-02-06-115032

In the above example, we have used the log method that offers the same capabilities as print, but adds some features useful for debugging a running application.

There are several other methods such as print, print_json, out, rule, and so on. Learn more about them here.

How to use Tree in Rich

Rich has a Tree class which can generate a tree view in the terminal. A tree view is a great way of presenting the contents of a filesystem or any other hierarchical data. Each branch of the tree can have a label which may be text or any other Rich renderable.

Let’s see an example by creating a family tree:

from rich.tree import Tree
from rich import print as rprint


tree = Tree("Family Tree")
tree.add("Mom")
tree.add("Dad")
tree.add("Brother").add("Wife")
tree.add("[red]Sister").add("[green]Husband").add("[blue]Son")

rprint(tree)

Output:

Screenshot-2022-02-06-121033

How to display a progress bar using Rich

Rich can show continuously updated information about the status of long-running tasks, file copies, and so forth. You can customize this information, too. By default, it provides a description of the ‘task,’ a progress bar, percentage complete, and anticipated time left.

Multiple tasks are supported with a rich progress display, each with a bar and progress statistics. You can use this to keep track of several jobs that are being worked on in threads or processes.

Let’s first try the progress.track method to create the progress bar.

from rich.progress import track
from time import sleep


def process_data():
    sleep(0.02)


for _ in track(range(100), description='[green]Processing data'):
    process_data()

Output:

progress

If we want to record the time when a particular task is finished executing, we can use console.status instead.

from rich.console import Console
from time import sleep

console = Console()

data = [1, 2, 3, 4, 5]
with console.status("[bold green]Fetching data...") as status:
    while data:
        num = data.pop(0)
        sleep(1)
        console.log(f"[green]Finish fetching data[/green] {num}")

    console.log(f'[bold][red]Done!')
progress-1

You can work directly with the Progress class if you need several tasks in the display or want to customize the columns in the progress display. After you’ve created a Progress object, use (add_task()) to add task(s) and (update_progress()) to update progress.

The Progress class is intended to be used as a context manager, automatically starting and stopping the progress display.

import time

from rich.progress import Progress

with Progress() as progress:

    task1 = progress.add_task("[red]Downloading...", total=100)
    task2 = progress.add_task("[green]Processing...", total=100)
    task3 = progress.add_task("[cyan]Installing...", total=100)

    while not progress.finished:
        progress.update(task1, advance=0.9)
        progress.update(task2, advance=0.6)
        progress.update(task3, advance=0.3)
        time.sleep(0.02)

Output:

progress-2

How to display Rich Columns in Python

Rich can render text or other Rich renderables in neat columns with the Columns class. To use, construct a Columns instance with an iterable of renderables and print it to the Console.

import json
from urllib.request import urlopen

from rich.console import Console
from rich.columns import Columns
from rich.panel import Panel


def get_content(user):
    """Extract text from user dict."""
    country = user["location"]["country"]
    name = f"{user['name']['first']} {user['name']['last']}"
    return f"[b]{name}[/b]n[yellow]{country}"


console = Console()


users = json.loads(urlopen("https://randomuser.me/api/?results=30").read())["results"]
user_renderables = [Panel(get_content(user), expand=True) for user in users]
console.print(Columns(user_renderables))

Output:

Screenshot-2022-02-06-124236

How to display Rich tables in Python

Rich’s Table class offers a variety of ways to render tabular data to the terminal. This class has add_column() and add_row() methods to add column and row respectively to the table instance created from the Table class.

Let’s create a table for our todo list. This table will have three columns – S.No., Task, and Status.

from rich.console import Console
from rich.table import Table

table = Table(title="Todo List")

table.add_column("S. No.", style="cyan", no_wrap=True)
table.add_column("Task", style="magenta")
table.add_column("Status", justify="right", style="green")

table.add_row("1", "Buy Milk", "✅")
table.add_row("2", "Buy Bread", "✅")
table.add_row("3", "Buy Jam", "❌")

console = Console()
console.print(table)

Output:

Screenshot-2022-02-06-190131

Wrapping Up

In this tutorial, we learned how to use Rich to beautify the terminal. There are lots of other features that Rich supports. Learn more about them in the official documentation.

Feel free to fork and play with the source code of this article here.

Thanks for reading!

Reference:

This post was inspired by a tutorial entry by freecodecamp.

You may also like

Leave a Comment