【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]
相关推荐
riverz122710 分钟前
‘Target closed‘ error in Puppeteer解决
linux
GineLee18 分钟前
吉林大学操作系统期末复习整理
linux·服务器·经验分享·架构·硬件工程·安全架构
和我乘风破浪21 分钟前
iOS自动化录屏在Chrome浏览器打不开处理方法
python·测试
就叫飞六吧37 分钟前
VMware安装Ubuntu并实现root远程登录
linux·运维·ubuntu
站大爷IP41 分钟前
当生成器遇上异步IO:Python并发编程的十大实战兵法
python
潇-xiao1 小时前
Makefile的通用模板 + 倒计时小程序(13)
linux·makefile
大明者省1 小时前
pycharm2020.2版本给项目选择了虚拟环境解释器,项目文件都运行正常,为什么terminal文件路径的前面没有虚拟解释器的名称
开发语言·python
love530love1 小时前
MSYS2 环境下 Python 开发配置(结合 PyCharm)使用笔记
人工智能·windows·笔记·python·pycharm·virtualenv·uv
站大爷IP1 小时前
用Python 3+Qt打造你的第一个对话框:从零开始的手把手教程
python
我叫黑大帅1 小时前
【Linux网络配置实验】Web配置
linux