How to create command line ML application with Typer and Python

Kiarash Kiani
2 min readFeb 20, 2021
Photo by Florian Klauer on Unsplash

This post will make a short introduction and a little example on the framework Typer: A Python-based framework, easy to build rich CLI application. In my opinion, Typer is a lifesaver for two reasons:

  1. It uses FastAPI coding style, So I don’t need to learn new framework architecture.
  2. It uses Type Hints to automatically build rich help commands, which leads to less writing code and saves me time.

Typer takes advantage of Python’s Decorators. Typer is enabled to pipe the user’s inputs from the selected command to your defined functions with decorators. Typer is also looked into the function parameters and their types to create helps automatically.

In the following, we are going to follow these steps to make a complete CLI application:

  1. Creating our first command with Typer
  2. Adding Optional arguments to our command
  3. Adding help description for our command

1. Creating our first command with Typer

The first step to make your CLI app is to instantiate from the Typer class, and then you will be able to define your commands with a decorator and a function.

In the Typer world, a command defines a function and its parameters by the function’s arguments. let us consider we want to let the user train the model with the following command:

python app.py train --epochs 100 --save true

2. Adding Optional arguments to our command

Suppose we always want to save the model by default unless the user force to not to:

As I said earlier, typer uses python type hinting for faster implementation. To mark variables to be able to have None values, we can use Optional syntax.

3. Adding help description for our command

The decorator’s help parameter adds a description for the command. It is also fruitful to add some explanation for some arguments made possible by the “typer.Option” function.

--

--