【问题标题】:Did Python 3.9 update how to type hint the function type?Python 3.9 是否更新了如何键入提示函数类型?
【发布时间】:2021-06-28 07:23:46
【问题描述】:

在 3.9 之前我会使用这个:

from typing import Callable

def my_function(argument_function: Callable) -> None:

现在我不确定了。

PEP 585 有一个不推荐使用的 Typing-types 列表,这些类型包括typing.Callable,但确实包括collections.abc.Callable。 到目前为止,我还没有使用 collections.abs 模块,但我想知道 typing.Callable 是否可能与 collections.abc.Callable 有关,因此也弃用了 Callable 类型提示。

我确实试过这个:

def my_function(argument_function: callable) -> None:

而且它有效。

但是现在这样真的是正确的方法吗? 还是我还需要导入typing.Callable

【问题讨论】:

  • 不,callable 不是类型。
  • 如果他们打算弃用 typing.Callable,他们会弃用 typing.Callable。该 PEP 专门用于减少冗余量 - 他们不希望两个 Callables 在两个不同的地方意味着相同的事情。
  • “它有效。” “它有效”是什么意思?它肯定不被 mypy 接受,它绝对不是规范的一部分
  • 这并不意味着什么。代码会 run 你使用任何东西,例如def my_function(argument_function: sum) -> None: 即使 sum 不是有效的类型注释。如果您使用半官方静态类型检查器 mypy 检查上述内容,您会得到 error: Function "builtins.callable" is not valid as a type... 因为正如我之前所说,callable 不是类型
  • 是的,您可能应该使用 fll 表单,Callable[[ArgTypes], ReturnType]

标签: python python-3.x type-hinting python-typing python-3.9


【解决方案1】:

由于没有答案,我将 juanpa.arrivillaga 的评论提升为答案。引用上述评论 [原文如此]:

您可能应该使用 fll 表单,Callable[[ArgTypes], ReturnType]

或充实它:

from typing import Callable

# Let's say this was an example of argument_function and that's 
# the signature that you expect in my_function

def foo(x: int) -> str:
    return str(x)

def my_function(argument_function: Callable[[int], str]) -> None:
    pass

【讨论】:

    猜你喜欢
    • 2022-08-05
    • 2021-12-06
    • 1970-01-01
    • 2023-03-28
    • 2021-08-14
    • 2019-09-01
    • 2021-03-23
    • 2019-07-08
    • 2022-10-20
    相关资源
    最近更新 更多