【python】typing用法

发布于:2025-06-21 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、基础类型提示

1. 基本类型注解

# 变量类型注解
age: int = 30
name: str = "Alice"
is_student: bool = False
height: float = 1.75

2. 函数注解

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

二、组合类型

1. 联合类型(Union)

from typing import Union

# value 可以是整数或浮点数
def format_number(value: Union[int, float]) -> str:
    return f"{value:.2f}"

# 或者使用简写 |(Python 3.10+)
def format_number(value: int | float) -> str:
    return f"{value:.2f}"

2. 可选类型(Optional)

from typing import Optional

def find_user(id: int) -> Optional[str]:
    # 返回值可以是字符串或 None
    return user_db.get(id, None)

三、容器类型

1. 列表(List)

from typing import List

# 整数列表
scores: List[int] = [90, 85, 95]

# 混合类型列表(不推荐,尽量避免)
values: List[Union[int, str]] = [1, "two", 3]

2. 元组(Tuple)

from typing import Tuple

# 固定结构元组
point: Tuple[float, float] = (3.5, 7.2)

# 可变长度元组
points: Tuple[float, ...] = (1.0, 2.5, 3.7)

3. 字典(Dict)

from typing import Dict

# 键为字符串,值为整数的字典
student_grades: Dict[str, int] = {"Alice": 90, "Bob": 85}

# 复杂字典
person: Dict[str, Union[str, int]] = {"name": "Alice", "age": 30}

四、特殊类型

1. 字面值类型(Literal)

from typing import Literal

# 参数只能是特定值
def set_direction(direction: Literal["up", "down", "left", "right"]) -> None:
    print(f"Moving {direction}")

set_direction("up")    # 正确
set_direction("north")  # 类型检查错误
# 注意:Python 的类型注解(包括 Literal)只对类型检查工具有效,不会影响实际运行,所以两个输出都正常。

2. 类型别名(TypeAlias)

# 创建类型别名(Python 3.10+)
from typing import TypeAlias

Coordinate: TypeAlias = Tuple[float, float]

def distance(a: Coordinate, b: Coordinate) -> float:
    return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5

五、泛型与高级类型

1. 可调用对象(Callable)

from typing import Callable

# 简单函数类型
Adder: Callable[[int, int], int] = lambda x, y: x + y


def add(x: int, y: int) -> int:
    return x + y

def apply_twice(func: Callable[[int, int], int], x: int, y: int) -> int:
    return func(func(x, y), func(x, y))

print(apply_twice(add, 2, 3)) # Output: 10
def create_adder(n: int) -> Callable[[int, int], int]:
    def add(x: int, y: int) -> int:
        return x + y + n
    return add

print(create_adder(5)(2, 3)) # Output: 10
    


2. Iterable, Sequence, Mapping

from typing import Iterable, Sequence, Mapping

# Iterable(可迭代对象)
def sum_all(values: Iterable[int]) -> int:
    return sum(values)

# Sequence(支持索引的集合)
def get_middle(items: Sequence[str]) -> str:
    return items[len(items)//2]

# Mapping(类似字典的结构)
def find_value(data: Mapping[str, int], key: str) -> int:
    return data.get(key, 0)

六、结构化类型

1. TypedDict(类型化字典)

from typing import TypedDict, List

class Person(TypedDict):
    name: str
    age: int
    hobbies: List[str]

alice: Person = {
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "hiking"]
}

2. NamedTuple(命名元组)

from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float
    z: float = 0.0  # 默认值

p = Point(1.5, 2.5)
print(p.x, p.y)  # 1.5 2.5

七、动态类型相关

1. Any(任意类型)

from typing import Any

def process_data(data: Any) -> Any:
    # 此函数接受和返回任何类型的值
    if isinstance(data, list):
        return data[0]
    return data

2. Type(类类型)

from typing import Type, TypeVar

T = TypeVar('T')

def create_instance(cls: Type[T]) -> T:
    return cls()

class Widget: pass
widget = create_instance(Widget)

十、Python 3.10+ 改进

Python 3.10 引入了更简洁的类型提示语法:

# 联合类型简化
def format_value(value: int | float | str) -> str:
    return str(value)

# 类型别名简化
type Coordinate = tuple[float, float]

# 参数化泛型
def first(items: list[T]) -> T:
    return items[0]

网站公告

今日签到

点亮在社区的每一天
去签到