7.5. Better Outputs#

7.5.1. How to Strip Outputs and Execute Interactive Code in a Python Script#

Hide code cell content
!pip install strip-interactive

Have you ever seen a tutorial with an interactive Python code and wished to execute it in a Python script like above?

It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. That is why I created strip-interactive.

from strip_interactive import run_interactive

code = """
>>> import numpy as np
>>> print(np.array([1,2,3]))
[1 2 3]
>>> print(np.array([4,5,6]))
[4 5 6]
"""

clean_code = run_interactive(code)
[1 2 3]
[4 5 6]

Link to the article about strip-interactive.

Link to strip-interactive.

7.5.2. Pyfiglet: Make Large and Unique Letters Out of Ordinary Text in Python#

Hide code cell content
!pip install pyfiglet

If you want to make large and unique letters out of ordinary text using Python, try pyfiglet. Below are some outputs of pyfiglet:

import pyfiglet
from termcolor import colored, cprint

out = pyfiglet.figlet_format("Hello")
print(out)
 _   _      _ _       
| | | | ___| | | ___  
| |_| |/ _ \ | |/ _ \ 
|  _  |  __/ | | (_) |
|_| |_|\___|_|_|\___/ 
                      
out = pyfiglet.figlet_format("Hello", font='slant')
print(out)
    __  __     ____    
   / / / /__  / / /___ 
  / /_/ / _ \/ / / __ \
 / __  /  __/ / / /_/ /
/_/ /_/\___/_/_/\____/ 
                       
cprint(pyfiglet.figlet_format('Hello', font='bell'), 'blue')
 __  __         .    .         
 |   |    ___   |    |     __. 
 |___|  .'   `  |    |   .'   \
 |   |  |----'  |    |   |    |
 /   /  `.___, /\__ /\__  `._.'
                               

This could be used as the welcome message for your Python package πŸ™‚

Link to pyfiglet.

Link to termcolor.

7.5.3. Python Fire: Generate a CLI for Any Python Objects in Two Lines of Code#

Hide code cell content
!pip install fire

Have you ever wanted to adjust the values of Python objects from the command line, but found it inconvenient to do so? With Python Fire, you can easily generate a command-line interface for any Python object in just two lines of code.

To see how Python Fire works, let’s look at an example. Start with creating file named fire_example.py:

%%writefile fire_example.py
import fire


def get_mean(numbers: list):
    return sum(numbers) / len(numbers)


def get_modulo(num1: int, num2: int):
    return num1 % num2


if __name__ == "__main__":
    fire.Fire()
Writing fire_example.py

Then run the following command on your terminal:

$ python fire_example.py get_mean "[1, 2, 3]"
2.0
$ python fire_example.py get_modulo --num1=3 --num2=2
1

Link to Python Fire.

7.5.4. Typer: Build a Command-Line Interface in a Few Lines of Code#

Hide code cell content
!pip install typer 

While Python Fire is easy to use, it doesn’t provide much flexibility in terms of customization. Typer offers tools for building CLI applications in Python with a more explicit syntax. Typer also uses type annotations to validate user input.

To see how Typer works, let’s look at an example. Start with creating file named typer_example.py:

%%writefile typer_example.py
import typer

app = typer.Typer()

@app.command()
def add_numbers(x: float, y: float):
    """Adds two numbers and prints the result."""
    result = x + y
    print(f"The sum of {x} and {y} is {result}.")

if __name__ == "__main__":
    app()
Writing typer_example.py

Then run the following command on your terminal:

$ python typer_example.py hello world

And you should see an output like below:

Hide code cell source
!python typer_example.py hello world
Usage: typer_example.py [OPTIONS] X Y
Try 'typer_example.py --help' for help.

Error: Invalid value for 'X': 'hello' is not a valid float.

You can see that when the input is not a valid float, Typer raised a TypeError with a helpful error message.

Providing the valid inputs will give the following output:

$ python typer_example.py 3 2
The sum of 3.0 and 2.0 is 5.0.

Link to Typer.

My full article about Typer.

7.5.5. Generate a Tree View with rich#

Hide code cell content
!pip install rich 

If you want to generate a tree view of a specific structure such as files in a directory, use rich.tree. rich also allows you to add color to each branch using brackets.

from rich.tree import Tree
from rich import print

tree = Tree("[cyan]My Project")
tree.add("[green]data")
tree.add("[blue]model")
src = tree.add("[red]src")
src.add("[red]process_data.py")
print(tree)
My Project
β”œβ”€β”€ data
β”œβ”€β”€ model
└── src
    └── process_data.py

Link to rich.

7.5.6. latexify_py: Generates a LaTex Math Description From a Python Function#

Hide code cell content
!pip install latexify-py

Have you ever wanted to add math description for your Python function but found it time-consuming to do so? latexify_py allows you to add LaTex math description with only one decorator.

import math
import latexify

@latexify.with_latex
def solve(a, b, c):
    return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

solve
\[ \displaystyle \mathrm{solve}(a, b, c)\triangleq \frac{-b + \sqrt{b^{2} - 4ac}}{2a} \]
@latexify.with_latex
def sinc(x):
    if x == 0:
        return 1
    else:
        return math.sin(x) / x

sinc
\[\begin{split} \displaystyle \mathrm{sinc}(x)\triangleq \left\{ \begin{array}{ll} 1, & \mathrm{if} \ x=0 \\ \frac{\sin{\left({x}\right)}}{x}, & \mathrm{otherwise} \end{array} \right. \end{split}\]

Link to latexify_py.

7.5.7. ManimML: Create Animations of Common ML Concepts in Python#

If you want to create animations and visualizations for common ML concepts in Python, try ManimML.

The GIF below is the visualization of Variational Autoencoder made by ManimML.

Link to ManimML.

ManimML is built on top of Manim.

7.5.8. Great Tables: Create Scientific-Looking Tables in Python#

Hide code cell content
!pip install great_tables 

If you want to create visually appealing and scientific-looking tables in Python, use Great Tables. With Great Tables, you can customize your table by mixing and matching various elements such as headers, footers, and cell value formats.

from great_tables import GT, md
from great_tables.data import islands

islands_mini = islands.head(10).sort_values(by="size", ascending=False) # pandas DataFrame

(
    GT(islands_mini, rowname_col="name")
    .tab_header(
        title="Large Landmasses of the World",
        subtitle="The top ten largest are presented",
    )
    .tab_source_note(
        source_note="Source: The World Almanac and Book of Facts, 1975, page 406."
    )
    .tab_source_note(
        source_note=md(
            "Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley."
        )
    )
    .tab_stubhead(label="landmass")
    .fmt_number(columns="size", sep_mark=",", decimals=0)
)
Large Landmasses of the World
The top ten largest are presented
landmass size
Asia 16,988
Africa 11,506
Antarctica 5,500
Australia 2,968
Borneo 280
Baffin 184
Britain 84
Celebes 73
Banks 23
Axel Heiberg 16
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.

Link to Great Tables.