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")
 _   _      _ _       
| | | | ___| | | ___  
| |_| |/ _ \ | |/ _ \ 
|  _  |  __/ | | (_) |
|_| |_|\___|_|_|\___/ 
out = pyfiglet.figlet_format("Hello", font='slant')
    __  __     ____    
   / / / /__  / / /___ 
  / /_/ / _ \/ / / __ \
 / __  /  __/ / / /_/ /
/_/ /_/\___/_/_/\____/ 
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__":
Writing fire_example.py

Then run the following command on your terminal:

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

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()

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__":
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")
src = tree.add("[red]src")
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

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

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

\[\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.