「PYTHON」- 注解 | Annotation

认识

注解 Annotation 是 Python 3.0 引入的语法特性,允许为函数参数、返回值和变量添加元数据信息。这些信息不会影响程序的执行,但可以提供类型提示和其他元数据。

注意,在 Python 中,类型注解(Type Annotations)不会在运行时强制变量类型。Python 仍然是一种动态类型语言,类型注解主要作用是提供类型提示,而不是强制类型检查。

性质

函数注解

def greet(name: str, age: int) -> str:
    return f"Hello {name}, you are {age} years old"

# 访问注解信息
print(greet.__annotations__)
# 输出: {'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}

带默认值的参数注解

def calculate_total(price: float, quantity: int = 1, discount: float = 0.0) -> float:
    return price * quantity * (1 - discount)

print(calculate_total.__annotations__)

变量注解

Python 3.6 引入了变量注解语法。

# 带初始值的变量注解
name: str = "Alice"
count: int = 0
is_active: bool = True

# 不带初始值的变量注解(需要在作用域内后续赋值)
score: float
score = 95.5

类中的注解

class Person:
    # 类属性注解
    name: str
    age: int
    email: str = "unknown@example.com"  # 带默认值
    
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

# 访问类的注解
print(Person.__annotations__)
# 输出: {'name': <class 'str'>, 'age': <class 'int'>, 'email': <class 'str'>}

应用

  • 使用类型注解:提高代码可读性和 IDE 支持
  • 配合 mypy:在开发过程中进行静态类型检查
  • 关键位置手动验证:在重要的 API 边界进行运行时类型检查
  • 文档说明:明确说明哪些地方会进行严格的类型检查

改进

typing

typing — Support for type hints https://docs.python.org/3/library/typing.html

复杂类型注解

from typing import List, Dict, Tuple, Set

# 列表注解
names: List[str] = ["Alice", "Bob", "Charlie"]
scores: List[float] = [95.5, 87.3, 92.1]

# 字典注解
person: Dict[str, any] = {"name": "Alice", "age": 30}
config: Dict[str, int] = {"timeout": 30, "retries": 3}

# 元组注解
coordinates: Tuple[float, float] = (40.7128, -74.0060)
person_info: Tuple[str, int, bool] = ("Alice", 30, True)

# 集合注解
unique_numbers: Set[int] = {1, 2, 3, 4, 5}

参考

DeepSeek / 介绍 Python 中的 Annotation