如何为Python函数声明自定义数据结构(字典列表)的返回值?
Python函数返回值类型标注指南
一、自定义数据结构的返回值标注
针对自定义数据结构,常用三种实用方式:
1. 用TypedDict定义固定结构的字典
如果返回值是键固定的字典,TypedDict能明确每个键的类型,让类型检查工具精准识别:
from typing import TypedDict # 定义自定义字典类型 class Product(TypedDict): name: str price: int def get_product() -> Product: return {"name": "book", "price": 55}
2. 用dataclasses定义类实例结构
如果自定义结构更适合用类承载,结合dataclasses可以创建轻量级数据类,天然支持类型标注:
from dataclasses import dataclass @dataclass class Product: name: str price: int def get_product() -> Product: return Product(name="book", price=55)
3. 用NewType创建类型别名
只是想给现有类型起自定义名称时,NewType能快速创建专属类型别名:
from typing import NewType ProductPrice = NewType("ProductPrice", int) def get_price() -> ProductPrice: return ProductPrice(55)
二、字典组成的列表的返回类型标注
针对你的示例场景,返回结果是元素为{字符串: 整数}的字典组成的列表,可以按版本选择标注方式:
Python 3.9+ 版本(原生泛型支持)
Python 3.9及以上允许直接用内置类型做泛型标注,无需额外导入模块:
x = [['book', 55], ['magazine', 30]] def my_function(x: list[list[str | int]]) -> list[dict[str, int]]: return [{i[0]: i[1]} for i in x] print(my_function(x))
这里list[list[str | int]]是对输入参数x的精确标注,说明它是包含字符串和整数子列表的列表;返回值list[dict[str, int]]明确了返回结构是键为字符串、值为整数的字典组成的列表。
Python 3.8及以下版本(需导入typing模块)
如果使用Python 3.8或更早版本,需要从typing模块导入泛型类型:
from typing import List, Dict, Union x = [['book', 55], ['magazine', 30]] def my_function(x: List[List[Union[str, int]]]) -> List[Dict[str, int]]: return [{i[0]: i[1]} for i in x] print(my_function(x))
内容的提问来源于stack exchange,提问作者Mehdi Zare
相关产品推荐
相关产品推荐

