类型 Hints
添加静态类型 annotations 使用类型 hints, 输入模块, and mypy for 类型检查.
你将学到
- Annotate 函数使用类型 hints
- Use 输入模块 for 复杂类型
- 理解可选, Union, and generics
- 运行 mypy for 静态类型检查
- Balance 类型 hints 使用 Python's 动态 nature
概念讲解
Basic Type Hints
Type hints (PEP 484) let you annotate the expected types of variables, parameters, and return values. They are optional and do not change runtime behavior — they are for static analysis tools like mypy:
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
age: int = 25
name: str = "Ada"
The syntax is 参数: 类型 for parameters and -> 类型 for return values. Python ignores these at runtime — they are metadata stored in __annotations__. Tools like mypy, pyright, and IDEs use them to catch type errors before you run the code.
Why Type Hints?
- Catch bugs early — mypy finds type errors before runtime
- Better IDE support — autocomplete, inline documentation, refactoring
- Self-documenting — the signature shows what types are expected
- Easier refactoring — the type checker verifies changes across the codebase
# Install and run mypy
pip install mypy
mypy my_script.py
Variables and Collections
# Variable annotations
count: int = 0
price: float = 19.99
name: str = "Ada"
is_active: bool = True
# Collection types (Python 3.9+ — use built-in types directly)
numbers: list[int] = [1, 2, 3]
names: list[str] = ["Ada", "Bob"]
scores: dict[str, int] = {"math": 90, "science": 85}
point: tuple[int, int] = (10, 20)
unique: set[str] = {"", "b", "c"}
In Python 3.9+, you can use 列表[int] directly. In 3.8 and earlier, you need 从 输入 导入 列表 and use 列表[int].
The typing Module
For more complex types, use the 输入 module:
from typing import Optional, Union, Any, Callable, Iterable
# Optional — either the type or None
def find_user(user_id: int) -> Optional[dict]:
# Returns a dict or None if not found
...
# Union — one of several types
def process(data: Union[str, bytes]) -> str:
...
# Any — any type (disables checking)
def debug(value: Any) -> None:
print(value)
# Callable — a function type
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
In Python 3.10+, you can use X | Y instead of Union[X, Y] and X | 无 instead of 可选[X]:
def find_user(user_id: int) -> dict | None:
...
def process(data: str | bytes) -> str:
...
Type Hints for Functions
from typing import List, Dict, Tuple
def process_items(items: List[str]) -> Dict[str, int]:
"""数量 occurrences 的每个字符串."""
result: Dict[str, int] = {}
for item in items:
result[item] = result.get(item, 0) + 1
return result
def split_point(p: Tuple[int, int]) -> Tuple[int, int]:
return p[0], p[1]
Generic Types with TypeVar
from typing import TypeVar, List
T = TypeVar("T") # T can be any type
def first(items: List[T]) -> T:
"""返回首先元素的 列表, preserving 类型."""
return items[0]
# mypy knows first([1, 2, 3]) returns int
# and first(["", "b"]) returns str
TypeVar lets you express relationships between types — " 返回类型 matches 列表元素类型." This is called generics and is powerful for reusable, type-safe functions.
TypedDict — Typed Dictionaries
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
email: str
user: UserDict = {"name": "Ada", "age": 25, "email": "[email protected]"}
# mypy checks that all required keys are present with the right types
TypedDict lets you type dictionaries with fixed keys — useful for JSON data and API responses.
Type Aliases
# Create a named alias for a complex type
UserID = int
UserMap = dict[UserID, str]
def get_name(users: UserMap, uid: UserID) -> str:
return users[uid]
Running mypy
# Check a file
mypy script.py
# Check a package
mypy -p mypackage
# Strict mode
mypy --strict script.py
# Common errors:
# error: Argument 1 to "添加" has incompatible type "str"; expected "int"
mypy catches type mismatches that would cause TypeError at runtime. Start with gradual typing — add hints to new code and critical functions first, then expand over time.
When to Use Type Hints
- Public APIs — library functions, class interfaces
- Complex functions — where the expected types are not obvious
- Team projects — where others benefit from the documentation
- New code — add hints as you write, not retroactively
Type hints are optional — you do not need them everywhere. Start with function signatures and expand as needed. Python remains dynamically typed; hints are a development aid, not a runtime enforcement.
示例代码
from typing import Optional, Union, Any, Callable, TypeVar, List, Dict
# Basic type hints
def greet(name: str, times: int = 1) -> str:
"""Greet someone, repeated."""
return (f"Hello, {name}! " * times).strip()
print(greet("Ada", 3))
# Optional and Union
def find_user(user_id: int) -> Optional[dict]:
users = {1: {"name": "Ada"}, 2: {"name": "Bob"}}
return users.get(user_id) # returns dict or None
result = find_user(1)
print(f"Found: {result}")
print(f"Not found: {find_user(99)}")
# Collection types
def count_words(words: List[str]) -> Dict[str, int]:
counts: Dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
print(count_words(["apple", "banana", "apple", "cherry", "banana", "apple"]))
# TypeVar — generics
T = TypeVar("T")
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3])) # mypy knows this returns int
print(first(["a", "b"])) # mypy knows this returns str
# Callable type
def apply_twice(func: Callable[[int], int], value: int) -> int:
return func(func(value))
print(apply_twice(lambda x: x + 3, 10)) # 16
# TypedDict for structured dicts
from typing import TypedDict
class User(TypedDict):
name: str
age: int
active: bool
user: User = {"name": "Ada", "age": 25, "active": True}
print(f"{user['name']}, age {user['age']}, active: {user['active']}")
# Variable annotations
count: int = 42
pi: float = 3.14159
tags: List[str] = ["python", "code"]
# Type alias
UserID = int
UserMap = Dict[UserID, str]
users: UserMap = {1: "Ada", 2: "Bob"}
print(f"User 1: {users[1]}")
Shows 基础函数 annotations, 可选/Union, 集合类型 (列表, Dict), TypeVar generics, Callable for 函数参数, TypedDict for structured dicts, 变量 annotations, and 类型 aliases.
动手试一试
- JSON Formatter
TypedDict and 类型 hints 是 useful for 输入 JSON 数据结构.
- 情况 Converter
类型 hints document 输入/输出类型的 conversion 函数.
常见错误
错误写法
Using 列表/Dict 从输入 in Python 3.9+ 相反的 构建-in 列表/dict
正确做法
In Python 3.9+, use 列表[int] and dict[str, int] directly 相反的 输入.列表 and 输入.Dict. 输入 versions 是 deprecated. For Python 3.8 and earlier, 你必须 use 输入模块 versions.
错误写法
Expecting 类型 hints 到是 enforced at 运行时
正确做法
类型 hints 是不 检查 at 运行时 — Python remains dynamically 输入. 它们是 metadata for 静态 analysis tools 如 mypy. 如果你 需要运行时类型检查, use 库如 pydantic or typeguard. 运行 mypy separately 到 catch 类型错误.
相关资源
相关速查表
- Python Cheatsheet
类型提示语法, 输入模块, and mypy usage.
练习 类型 Hints
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。