【问题标题】:code typing : how to type an input that can be of multiple types? [duplicate]代码输入:如何输入可以是多种类型的输入? [复制]
【发布时间】:2023-01-12 21:44:31
【问题描述】:

假设我有一个可以接受 int 或 None 的函数。你会怎么写呢?

def func(x: int or None):
   return x

【问题讨论】:

  • 在那种情况下@Chris 不会Optional 仍然更好吗?
  • @matszwecja,是的。由于 None 是备选方案之一,因此 Optional 更好。对于其他类型的工会,| is preferred in Python 3.10+

标签: python typing


【解决方案1】:

使用Union

from typing import Union
def func(x: Union[int, None]):
   return x

请参阅此处的文档:https://docs.python.org/3/library/typing.html#typing.Union

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2016-09-20
    • 2016-05-17
    • 1970-01-01
    • 2018-03-28
    相关资源
    最近更新 更多