Python Glossary Русский

Python 3.0+Functionsfunction

Type hints

annotations

Type hints for parameters and return values. They do not affect execution, but they help IDEs and mypy.

Syntax

def f(x: int) -> str: ...

Annotations are just metadata: Python stores them in __annotations__ and never checks them itself, so passing a str where an int is declared raises no error — only mypy will flag it. That same metadata powers dataclasses and pydantic, which read annotations at runtime. Since Python 3.14 annotations are evaluated lazily, so a class that isn't defined yet can be referenced by its bare name; on older versions put its name in quotes.

Examples

def greet(name: str) -> str:
    return f'Hello, {name}'
print(greet('Alice'))  # → Hello, Alice
def add(a: int, b: int) -> int:
    return a + b
print(add(2, 3))  # → 5
from typing import Optional
def find(lst: list, val: int) -> Optional[int]:
    try:
        return lst.index(val)
    except ValueError:
        return None
print(find([1,2,3], 2))  # → 1
from typing import Union
def double(x: Union[int, float]) -> Union[int, float]:
    return x * 2
print(double(3.5))  # → 7.0
from typing import List, Dict
def total(prices: List[float]) -> float:
    return sum(prices)
print(total([1.5, 2.5, 3.0]))  # → 7.0
# Python 3.10+ синтаксис
def clamp(x: int | float, lo: int | float, hi: int | float) -> int | float:
    return max(lo, min(x, hi))
print(clamp(5, 0, 3))  # → 3
# Variable annotations
count: int = 0
name: str
# Python 3.9+
def get_items() -> list[int]:
    return [1, 2, 3]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy