Open In App

Python Typer Module

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads