python - 使用非类型对象注释参数

标签 python python-3.x annotations type-hinting

我正在开发一个框架,它采用 python 函数并将它们转换为容器化程序。 我需要一种用一些扩展信息来注释函数参数的方法。 为此,我开始使用 Python 的“参数注释”/“类型提示”。 然而,我听到一些传言说,将来非类型的注释将变得非法。真的吗? 我的框架可以在注释中使用非类型对象吗?

def my_func(
    param1: 'foo',
    param2: 'foo bar',
    param3: {'a' : 1},
):
    pass

最佳答案

当 PEP-484 发布时,它特别允许继续使用函数注释来实现您喜欢的任何目的:

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

如果使用注释进行提示,PEP-484 只是标准化了类型提示的外观。

<小时/>

然而,PEP-563 包含一条似乎与此相矛盾或覆盖的注释:

Non-typing usage of annotations

While annotations are still available for arbitrary use besides type checking, it is worth mentioning that the design of this PEP, as well as its precursors (PEP 484 and PEP 526), is predominantly motivated by the type hinting use case.

In Python 3.8 PEP 484 will graduate from provisional status. Other enhancements to the Python programming language like PEP 544, PEP 557, or PEP 560, are already being built on this basis as they depend on type annotations and the typing module as defined by PEP 484. In fact, the reason PEP 484 is staying provisional in Python 3.7 is to enable rapid evolution for another release cycle that some of the aforementioned enhancements require.

With this in mind, uses for annotations incompatible with the aforementioned PEPs should be considered deprecated.

不过,我在 563 之后没有看到任何提及函数注释的 PEP,只有变量注释。

<小时/>

暂时建议您可以继续使用函数注释,只要您知道这种使用与 等工具不兼容即可mypy.

事实上,from __future__ import comments 会停止对注释的求值,并将它们视为原始字符串(这将成为 Python 4 中的默认行为),这表明如果您现在坚持使用字符串,使用非类型提示注释将继续不会产生运行时后果。 (也就是说,不要依赖您的注释来实际评估。)

关于python - 使用非类型对象注释参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060725/

相关文章:

python - 重定义对象的方法

python - 如何使用 urllib 发送 cookie

python - 使用 `loc` 进行 Pandas bool 选择并不总是更快?

python - 仅沿一个轴平滑二维阵列

python - =+ Python 运算符在语法上是正确的

java - Android Studio (0.8.2) + Android Annotations (3.0.1) cannot symbol class MyClass

java - Java如何实现注解(元数据)中声明的方法?

python - 使用 Python 设置和压缩问题

python - 什么时候以及为什么我应该使用 attr.Factory?

java - 编写java注解用于计时方法调用