Open In App

Type Hints in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Type hints are a feature in Python that allow developers to annotate their code with expected types for variables and function arguments. This helps to improve code readability and provides an opportunity to catch errors before runtime using type checkers like mypy.

Using Type Hints in Python

1. Variable and Function Type Hints

Type hints define the expected type for variables and function arguments. Example:

Python
age: int = 25
def greet(name: str) -> str:
    return f"Hello, {name}!"

Explanation:

  • age is an integer (int).
  • greet function expects a string (name: str) and returns a string (-> str).

2. Function Return Type

The return type of a function can be specified using ->. Example:

Python
def add_numbers(x: int, y: int) -> int:
    return x + y

Explanation: The add_numbers function expects two integers (x: int, y: int) and returns an integer (-> int).

3. Optional Types and Collections

Use Optional for values that can be None, and define types for collections like lists and tuples. Example:

Python
from typing import Optional, List, Tuple

def get_user(id: int) -> Optional[str]:
    return None if id == 0 else "User"

def sum(num: List[int]) -> int:
    return sum(num)

def get_name_and_age() -> Tuple[str, int]:
    return ("Abc", 25)

Explanation:

  • Optional[str]: The get_user function can return either a string or None.
  • List[int]: The sum_numbers function expects a list of integers.
  • Tuple[str, int]: The get_name_and_age function returns a tuple with a string and an integer.

Example Without Type Hints

Here’s an example of a factorial function without type hints:

Python
def factorial(i):
    if i < 0:
        return None
    if i == 0:
        return 1
    return i * factorial(i - 1)

print(factorial(4))
print(factorial("4"))
print(factorial(5.01))

Output

withoutTypeHints
Output without Type Hints

Explanation:

  • The function works fine with integers.
  • It throws an error if a string is passed (since you cannot perform mathematical operations on strings).
  • It also throws an error with floating-point numbers. For instance, passing 5.01 will eventually lead to an issue where the function tries to decrement the number until it reaches a non-integer value, causing it to return None and break the logic.

Adding Type Hints

By adding type hints, we can make the function’s expected behavior more clear. Here’s the modified code with type hints:

Python
def factorial(i: int) -> int:
    if not isinstance(i, int):  
        return None
    if i < 0:
        return None
    if i == 0:
        return 1
    return i * factorial(i - 1)

print(factorial(5.01)) 

Output
None

Explanation: In this version, if the input isn't an integer, the function will return None instead of causing an error.

Why Type Hints Don’t Prevent Errors

Type hints are not enforced by the Python interpreter; they are purely for static analysis by external tools like mypy. So, even with type hints, the code will still run with errors unless a static type checker is used. Python won’t prevent you from passing a string or floating-point number to the function at runtime.

Using mypy for Type Checking

To actually check if your code violates any type hints, you can use a tool like mypy, a static type checker for Python. Running mypy on your script will not execute the code but will analyze it for type hint violations. For example, let's check the factorial function with mypy:

1. Install mypy: If you don't have mypy installed, you can install it using pip:

pip install mypy

2. Run mypy on your script: Now, you can run the following command:

mypy ranking.py

This will analyze your code and give a clear error message if the types don’t match, like:

Error Message

Next Article
Practice Tags :

Similar Reads