Type hints
- Version
- 3.14
- Review
- Draft
Summary#
Type hints describe expected types for type checkers and editors. The Python runtime does not enforce them. A Protocol describes a type by its members, so matching classes need not inherit from it.
Syntax#
def load(path: str, limit: int | None = None) -> list[str]:
...
type Matrix = list[list[float]]
Example#
from typing import Protocol
class Named(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
type Prefix = str | None
def describe(item: Named, prefix: Prefix = None) -> str:
return f"{prefix or 'item'}: {item.name}"
def double(value: int) -> int:
return value * 2
print(describe(User("Ada")))
print(describe(User("Ada"), "user"))
print(double("ha"))
print(sorted(double.__annotations__))
Expected output#
item: Ada
user: Ada
haha
['return', 'value']
Common mistakes#
An annotation does not validate input: double("ha") runs and repeats the string even though the hint says int. Run a type checker for static checks, and validate external data with runtime code.
Version applicability#
Python 3.14 evaluates annotations on demand. Forward references can be unquoted when the names exist by evaluation time. Modules that use from __future__ import annotations still turn their annotations into strings. Protocol requires Python 3.8. Evaluating list[str] requires 3.9 and X | Y requires 3.10. The type statement sets the minimum for the example at 3.12.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0