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 Modules Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python subprocess module The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. In this tutorial, weâll delve into how to effective
9 min read
Python Math Module Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python Module Index Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
Reloading modules in Python The reload() is a previously imported module. If you've altered the module source file using an outside editor and want to test the updated version without leaving the Python interpreter, this is helpful. The module object is the return value. Reloading modules in Python2.xreload(module)For above 2.
1 min read
Import module in Python In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Pythonâs import st
3 min read
__future__ Module in Python __future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. I
4 min read
How to Install a Python Module? A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. What is a Python Module?A module can be imported by multiple programs for their application, hence a single code can be used by multiple pr
4 min read
Basics Of Python Modules A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard li
3 min read
Where Does Python Look for Modules? Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module in that file and then we can use them. Modules can exist in various directories. In this article, we will discuss where do
3 min read