CLI Development in Python with Typer
Nuno Bispo
Creating Command Line Interface (CLI) applications in Python has never been more accessible
Creating Command Line Interface (CLI) applications in Python has never been more accessible, thanks to the introduction of Typer.
Developed by Sebastián Ramírez, the mind behind the fast and modern web framework FastAPI, Typer leverages Python 3.6+ type hints to make CLI development intuitive and efficient.
This article dives into Typer, showcasing its installation process, fundamental concepts, and several application examples to illustrate its versatility and power.
Installation
Getting started with Typer is straightforward. Ensure you have Python 3.6 or newer installed on your machine, and then install Typer via pip, Python's package manager.
Open your terminal or command prompt and run the following command:
pip install typer
This command downloads and installs Typer and its dependencies, setting you up for developing your CLI applications.
Basic Example: Hello World
Let's kick things off with a classic "Hello World" example. This simple application will greet the user by name.
import typer
def main(name: str):
typer.echo(f"Hello {name}")
if __name__ == "__main__":
typer.run(main)
In this snippet, typer.run(main)
tells Typer to execute the main
function when the script is run.
The name: str
argument uses type hints to specify that name
should be a string, which Typer uses to automatically parse and validate command-line arguments.
Advanced Usage: Commands and Options
Typer supports creating applications with multiple commands and options, akin to how Git or Docker works.
Here's an example with a CLI tool that can perform addition and subtraction:
import typer
app = typer.Typer()
@app.command()
def add(x: float, y: float):
typer.echo(f"The sum is: {x + y}")
@app.command()
def subtract(x: float, y: float):
typer.echo(f"The difference is: {x - y}")
if __name__ == "__main__":
app()
Here, typer.Typer()
creates a new Typer application, and the @app.command()
decorator marks functions as CLI commands.
Running this script with add 5 3
will output "The sum is: 8", while subtract 5 3
will output "The difference is: 2".
Options with Default Values
Typer allows for command options with default values, enhancing command flexibility.
Consider this enhanced "Hello World" that includes a polite option:
import typer
def main(name: str, formal: bool = False):
if formal:
typer.echo(f"Good day, Mr. {name}.")
else:
typer.echo(f"Hello {name}!")
if __name__ == "__main__":
typer.run(main)
Running this script with --formal
will trigger the formal greeting.
For example, python script.py John --formal
outputs "Good day, Mr. John."
Conclusion
Typer stands out in the Python ecosystem for its simplicity, elegance, and the sheer productivity it offers developers.
By leveraging Python's type hints, it reduces boilerplate code and automatically generates help text, making CLI development a breeze.
Whether you're building simple tools or complex applications with multiple commands and options, Typer provides the flexibility and power needed to get the job done efficiently.
With its intuitive syntax and comprehensive documentation, Typer is an excellent choice for any developer looking to create CLI applications in Python