PIP-Talk - Week 36

Every week going forward I plan to write a little about interesting modules/libraries available for Python.

The topic for this week is: Typer

Typer is a great way to implement CLI support for your new or previous applications, with a minimal effort. It utilize the Click library and Python type hints to generate easy and built in help support with minimal needed changes in your code.


Background: Typer

Typer is a library for building Command Line Interface (CLI) applications based on Python’s type hints.
Built on top of Click and created by Sebastián Ramírez, the author of FastAPI.

Key features

  • Easy to use and learn.
  • Short: Minimize code duplication.
  • Simple: The simplest example adds only 2 lines of code to your app: 1 import, 1 function call.

Whats the use case, what problem does it solve ?

Building command line interface (CLI) applications with minimal effort.


Example code

Here is a simple example with two functions added to the CLI. Each of the function is prefixed with the line: @app.command()

import typer

app = typer.Typer()


@app.command()
def hello(name: str):
    print(f"Hello {name}")


@app.command()
def goodbye(name: str, formal: bool = False):
    if formal:
        print(f"Goodbye Ms. {name}. Have a good day.")
    else:
        print(f"Bye {name}!")


if __name__ == "__main__":
    app()

Output

Here we add the –help flag, to get some help about the expected options for the hello command.

python example1.py hello --help

Result

This is the generated result, where Typer fetch the expected format (via python type hints) and display this to the user.

Usage: example1.py hello [OPTIONS] NAME

Arguments:
  NAME  [required]

Options:
  --help  Show this message and exit.

Sources


Install

pip install "typer[all]"