Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python subprocess module
Next article icon

Python Typer Module

Last Updated : 21 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Python subprocess module

D

dhruva3223
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python sys Module
    The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. Let's consider the
    6 min read
  • Python String Module
    The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines vario
    4 min read
  • 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
    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 Fire Module
    Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
    3 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
  • Python datetime module
    In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
    14 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences