【python】typing用法

一、基础类型提示

1. 基本类型注解

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

2. 函数注解

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

二、组合类型

1. 联合类型(Union)

python 复制代码
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)

python 复制代码
from typing import Optional

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

三、容器类型

1. 列表(List)

python 复制代码
from typing import List

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

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

2. 元组(Tuple)

python 复制代码
from typing import Tuple

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

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

3. 字典(Dict)

python 复制代码
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)

python 复制代码
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 复制代码
# 创建类型别名(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)

python 复制代码
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

python 复制代码
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(类型化字典)

python 复制代码
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(命名元组)

python 复制代码
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(任意类型)

python 复制代码
from typing import Any

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

2. Type(类类型)

python 复制代码
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 引入了更简洁的类型提示语法:

python 复制代码
# 联合类型简化
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]
相关推荐
代码游侠5 分钟前
学习笔记——线程控制 - 互斥与同步
linux·运维·笔记·学习·算法
yaoh.wang9 分钟前
力扣(LeetCode) 66: 加一 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
牛奶咖啡1315 分钟前
Linux常见系统故障案例说明并修复解决(下)
linux·服务器·文件系统挂载异常分析并修复·持久化挂载分区文件丢失故障修复·分析系统进程cpu占用率过高
java_logo28 分钟前
Webtop Docker 容器化部署指南:基于浏览器的Linux桌面环境
linux·docker·容器·webtop·webtop部署教程·docker部署webtop·linux桌面
田姐姐tmner35 分钟前
Python 全面语法指南
开发语言·python
^_scv_^42 分钟前
QEMU-RISCV平台opensbi代码分析(2)
linux·架构·risc-v
white-persist1 小时前
【攻防世界】reverse | simple-check-100 详细题解 WP
c语言·开发语言·汇编·数据结构·c++·python·算法
王大傻09281 小时前
Series的属性简介
python·pandas
OliverH-yishuihan1 小时前
在 Windows 上安装 Linux
linux·运维·windows
zclinux_1 小时前
【Linux】虚拟化的内存气泡
linux·运维·服务器