首页 > 解决方案 > Python:如何注释变量,它可以包含任何类型的通用别名,如 Union、List 等?

问题描述

那么,如何注释变量或函数 arg,它可以包含任何类型的通用别名,如 Union、List 等,即可以用于某些合理类型注释的东西,例如在 pydantic 模型中?

from typing import Union, Tuple, List


def f(x: 'What is there?'): ...

f(Union[int, str]) # should be ok
f(Tuple[int, str]) # should be ok
f(List[int]) # should be ok
f(1) # should be NOT ok

标签: pythongenericstypesmypy

解决方案


推荐阅读