7.5. Better Outputs#
7.5.1. How to Strip Outputs and Execute Interactive Code in a Python Script#
Show 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]
7.5.2. Pyfiglet: Make Large and Unique Letters Out of Ordinary Text in Python#
Show 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 π
7.5.3. Python Fire: Generate a CLI for Any Python Objects in Two Lines of Code#
Show 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
7.5.4. Typer: Build a Command-Line Interface in a Few Lines of Code#
Show 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:
Show 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.
7.5.5. Generate a Tree View with rich#
Show 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
7.5.6. latexify_py: Generates a LaTex Math Description From a Python Function#
Show 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
@latexify.with_latex
def sinc(x):
if x == 0:
return 1
else:
return math.sin(x) / x
sinc
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.
ManimML is built on top of Manim.