【python】typing用法

一、基础类型提示

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]
Pythontyping模块是为类型提示(Type Hints)提供运行时支持的模块。它在Python 3.5版本开始作为标准库引入\[1\]。在Python中,由于是一门弱类型的语言,很多时候我们可能不清楚函数参数类型或者返回值类型,这可能导致一些类型没有指定方法。typing模块可以很好地解决这个问题\[2\]。它可以在不影响程序运行的情况下提供类型提示,只是作为一种提醒的方式存在。 在typing模块中,TypeVar是一个很有用的工具。它类似于C++中的template,可以用来限制多个变量为同一个数据类型\[3\]。通过使用TypeVar,我们可以在函数定义中指定参数的类型,以及函数的返回值类型。例如,在给定的代码示例中,T和A都是通过TypeVar定义的类型变量。T可以是任何类型,而A必须是str或bytes类型。这样,我们可以在函数定义中使用这些类型变量来指定参数类型和返回值类型。 总结起来,typing模块为Python提供了类型提示的运行时支持,可以帮助我们在代码中指定参数类型和返回值类型,以提高代码的可读性和可维护性。 #### 引用[.reference_title] - *1* [Python3中typing模块介绍](https://blog.csdn.net/fengbingchun/article/details/122288737)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python模块分析:第3节-typing模块](https://blog.csdn.net/weixin_34221073/article/details/88685704)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Pythontyping模块](https://blog.csdn.net/qq_62789540/article/details/124790174)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值