Type Hints for Python (Backport)

3.10.0.0 · active · verified Thu Apr 09

The `typing` library provides type hints for Python. The `typing` *package* on PyPI (version 3.10.0.0) is a backport of the standard library `typing` module, designed specifically for Python versions older than 3.5. It allows developers to add type annotations to their code for improved readability, maintainability, and static analysis by tools like MyPy. The `typing` *module* became a standard part of Python 3.5 (PEP 484) and has since received continuous enhancements and new features in subsequent Python releases. The PyPI package's versioning often reflects the Python version whose typing features it aims to backport.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic type hinting using common constructs from the `typing` module, including type annotations for variables, function parameters, and return values. It also shows the use of `List`, `Optional`, and `Union` types for more complex scenarios. The `from __future__ import annotations` import is recommended for broader compatibility and allows for 'postponed evaluation' of type annotations.

from __future__ import annotations # For Python < 3.9, enables future syntax for type hints
from typing import List, Union, Optional

def greet(name: str) -> str:
    return f"Hello, {name}!"

def get_item(items: List[str], index: int) -> Optional[str]:
    if 0 <= index < len(items):
        return items[index]
    return None

def process_value(value: Union[int, str]) -> str:
    if isinstance(value, int):
        return f"Received an integer: {value}"
    return f"Received a string: {value}"

print(greet("Alice"))
print(get_item(["apple", "banana"], 0))
print(get_item(["apple", "banana"], 2))
print(process_value(123))
print(process_value("hello"))

view raw JSON →