Python类型提示中能否用管道符号表示两种以上类型?
关于Python类型标注中管道符(|)与Union的使用问题
你编写的代码:
def foo(x: int | float | str): pass foo(0)
运行后出现的错误:
TypeError: unsupported operand type(s) for |: 'type' and 'type'
相关问题的说明:
- 用
|表示多类型联合是Python 3.10及以上版本才支持的语法,低版本Python不兼容这个写法,所以会触发报错。 - 在Python 3.10+环境中,
int | float | str这种管道符写法完全有效,和typing.Union[int, float, str]的功能完全一致,写法更简洁。 - 如果你的Python版本低于3.10,必须使用
Union来实现多类型标注,代码需修改为:from typing import Union def foo(x: Union[int, float, str]): pass foo(0)
内容的提问来源于stack exchange,提问作者AlwaysLearning
相关产品推荐
相关产品推荐

