如何为Python的settings_traversal函数正确定义返回类型?
正确定义settings_traversal函数的返回类型
你的原代码中,settings_traversal的返回类型定义不符合实际逻辑:函数实际返回的是元素为元组的列表,每个元组由str、bool、Type[BaseCountryRatingComponent]中的任意类型组成(长度不限),但原返回类型写的是单个类型的列表,无法匹配实际返回结构。
解决方案
要正确定义这种返回类型,需要结合tuple(Python 3.9+支持原生标注)/Tuple(Python 3.8及以下)、Union和可变长度标记...,表示元组可以包含任意数量的指定类型元素。
修正后的代码示例
- Python 3.9+版本(支持原生类型标注):
from typing import Union, Type class BaseCountryRatingComponent: pass class ComponentSetting: pass class CompositeComponentSetting: pass def settings_traversal( settings: list[Union["ComponentSetting", "CompositeComponentSetting"]], query_params: list[str], ) -> list[tuple[Union[str, bool, Type["BaseCountryRatingComponent"]], ...]]: pass def get_model_and_orm_key( self, ) -> list[tuple[Type["BaseCountryRatingComponent"], str]]: return settings_traversal(settings, ["model", "orm_key"])
- Python 3.8及以下版本:
from typing import Union, Type, Tuple, List class BaseCountryRatingComponent: pass class ComponentSetting: pass class CompositeComponentSetting: pass def settings_traversal( settings: List[Union["ComponentSetting", "CompositeComponentSetting"]], query_params: List[str], ) -> List[Tuple[Union[str, bool, Type["BaseCountryRatingComponent"]], ...]]: pass def get_model_and_orm_key( self, ) -> List[Tuple[Type["BaseCountryRatingComponent"], str]]: return settings_traversal(settings, ["model", "orm_key"])
类型说明
tuple[Union[str, bool, Type["BaseCountryRatingComponent"]], ...](或Tuple[Union[...], ...]):表示元组可包含任意数量的元素,每个元素的类型是str、bool或Type[BaseCountryRatingComponent]中的一种,完美匹配你描述的tuple[str]、tuple[str, str]、tuple[Type[BaseCountryRatingComponent], bool]等所有情况。- 外层的
list[...]明确函数返回的是由上述元组组成的列表,完全贴合函数的实际返回逻辑。
内容的提问来源于stack exchange,提问作者Olexiy Kutsenko
相关产品推荐
相关产品推荐

