Typer is a library for building powerful command-line interface applications in the easiest way. It is easier to read and the simplest way to create a command line application rather than using the standard Python library argparse, which is complicated to use. It is based on Python 3.6+ type hints and is built on top of Click(Typer inherits most of the features and benefits of Click), which is a Python package to build a command-line interface. The module also provides automatic help and automatic completion for all the shells. Furthermore, it is short to write and easy to use.
Installation
To install the Typer module, you need to open up your terminal or command prompt and type the following command:
pip install typer
After installing the typer module, we are ready to create a simple command-line interface.
Calling typer Function
Here’s an example of calling typer on a function. We will make a function and call the function in CLI. This is a program that will display the message "Hello World!" in the command-line interface.
Python3
# Python program to print "Hello World!"
import typer
# Function
def main():
print(f"Hello World")
typer.run(main)
Input:
Here, gfg.py is the file name of the script that is needed to be executed
Output:
Hello World!
Pass Arguments in Python typer Module from CLI
Let's modify our program to pass the argument to the main function. The following example has one argument name. When the function is called, we pass "World!" along the parameter name.
Python3
# Python program to print "Hello World!"
# By taking passing argument
# value as "World!" in parameter name
import typer
# Function having parameter name
def main(name):
print(f"Hello {name}")
typer.run(main)
Input:
Here's how we can pass "World!" along the parameter name.
$ python gfg.py World!
Output:
Hello World!
Getting Help information in typer Module
Typer help is used to display the documentation of the typer python script. It displays arguments, options, descriptions, etc.
Python3
import typer
app = typer.Typer()
@app.command()
def gfg(string: str = typer.Argument(..., help = """Prints input string""")):
"""Prints geeksforgeeks and input string"""
print("@geeksforgeeks")
print(string)
app()
Input:
Typer help can be used by typing --help after python [filename.py].
$ python gfg.py --help
Output:
Here, documentation and arguments of the typer Python script are generated.
Usage: gfg.py [OPTIONS] NUMBER
Prints geeksforgeeks and input string
Arguments:
STRING Prints input string [required]
Add Argument
Typer supports various data types for CLI options and CLI arguments.
Python3
# Python program to take multiple
# inputs of different datatypes and print it
import typer
# Function with multiple parameters
def details(display: bool, name: str, age: int,
marks: float, country: str = "India"):
print(f"Country: {country}")
if display == True:
print("@geeksforgeeks")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Marks: {marks}")
typer.run(details)
Input:
Here display (bool) = True, name (str) = gfg, age (int) = 20, marks (float) = 94.57 and keeping country parameter as default that is "India".
$ python gfg.py True gfg 20 94.57
Output:
Country: India
@geeksforgeeks
Name: gfg
Age: 20
Marks: 94.57
If you want to change the country parameter value, you could type the command as
Input:
$ python gfg.py True gfg 20 94.57 ---country Bhutan
Output:
Country: Bhutan
@geeksforgeeks
Name: gfg
Age: 20
Marks: 94.57
Python Program to use typer options and prompt user with [yes/no]
Typer option is similar to arguments, but it has some extra features.
Python3
import typer
app = typer.Typer()
@app.command()
# You can input a default value like
# 'True' or 'False' instead of '...'
# in typer.Option() below.
def square(name,language: bool = typer.Option(
..., prompt = "Do You Want to print the language"),
display: bool = False):
print("@geeksforgeeks")
if display == True:
print(name)
if language == True:
print("Python 3.6+")
app()
Input:
$ python gfg.py gfg --display
Output:
Here, display (bool) has the value True when --display is used and the language is printed when the input for the prompt is 'y'.
Do You Want to print the language [y/n]: y
@geeksforgeeks
gfg
Python 3.6+
Input:
$ python gfg.py gfg --no-display
Output:
Here, display (bool) has the value False when --no-display is used and the language is not printed when the input for the prompt is 'n'.
Do You Want to print the language [y/n]: n
@geeksforgeeks
You can try out different combinations of commands and can learn more about these combinations using the --help command.
Executing Multiple Commands using Python typer Module
Till now, we have only used a single function in all of the above programs. We will now see how to use multiple functions in the command line.
Python3
# Python program to print
# square or cube of a number
import typer
app = typer.Typer()
@app.command()
def square(number: int):
print(number*number)
@app.command()
def cube(number: int):
print(number*number*number)
app()
Input:
Here the square function is called and prints the square of 3.
$ python gfg.py square 3
Output:
9
Input:
Here, the cube() function is called and prints the cube of 3.
python gfg.py cube 3
Output:
27
Auto-completion Using Python typer module
This will create a typer command that we be able to call in our terminal like python, git, etc.
$ pip install typer-cli
And finally, we can install completion for the current shell, and it won't be required to install it again in the future.
$ typer --install-completion
Now, we are ready to use the typer feature autocompletion. We just need to use typer command instead of the python command and also add run command after the filename in the CLI.
Here's how we can run the script in typer CLI.
typer [filename.py] run [function]
The function is auto-completed when we press the Tab key.
Note: To make the auto-completion work, there should not be any call to app(). If you do not remove this line, it'll give RecursionError.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read