【问题标题】:How to express python callable type without determining return type?如何在不确定返回类型的情况下表达python可调用类型?
【发布时间】:2021-10-26 22:43:48
【问题描述】:

我有一个函数返回另一个函数,但返回函数的返回类型不清楚。为了表示函数返回类型,我们可以使用Callable[[], ReturnType],为了不强调参数,我们可以这样做Callable[..., ReturnType]。但我希望这个ReturnType 不能确定。

我该怎么办?

我的代码是这样的:

def funcA() -> int:
  return 2

def funcB() -> str:
  return 'b'

def f(inp: int) -> Callable[[], X] # <--- what should X be Here?
  return funcA if inp == 0 else funcB

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:

    理论上f返回intstr,所以返回类型应该是typing.Union[int, str]

    如果您不想指定返回类型,则可以使用typing.Any

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-19
      • 2016-11-13
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多