You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:15:44