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.



Similar Reads

Os Module Vs. Sys Module In Python
Python provides a lot of libraries to interact with the development environment. If you need help using the OS and Sys Module in Python, you have landed in the right place. This article covers a detailed explanation of the OS and Sys Module including their comparison. By the end of this article, you will be able to easily decide which module suits
5 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
median() function in Python statistics module
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() fun
4 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
Article Tags :
Practice Tags :