如何指定一个属性必须是一个(比方说)整数列表,而不仅仅是一个列表?

How to specify that an attribute must be a list of (say) integers, not just a list?

使用 attrs libary 和 Python 3.6,我认为以下内容允许我指定 xy 只能包含整数:

import attr

@attr.s
class C:
  x : List[int] = attr.ib()   # not working
  y = attr.ib(type=List[int]) # not working either

两条注释行都抛出 NameError: name 'List' is not defined.

我希望它起作用的原因如下:

(1) types section of the attr documentation 包括以下段落:“attrs 还允许您使用 attr.ib() 的类型参数或 –从 Python 3.6 开始——使用 PEP 526 注释”。然后它演示了这两种方法:

@attr.s
class C:
    x = attr.ib(type=int)
    y: int = attr.ib()

(2) PEP 526 声明以下类型注释语法有效:primes: List[int] = [].

语法确实有效。但是PEP 484 are not in the builtins namespace, but in the typing模块添加的泛型注解对象。

因此,您需要按照您链接的 attrs 文档以及 PEP 484、PEP 483、PEP 526 和 typing 文档中的所有示例进行操作:

from typing import List

另请注意,这只是一个注释。你仍然可以写 c = C(x=[], y=[1.0]) 而你不会得到 TypeError。正如您链接的文档所说:

attrs itself doesn’t have any features that work on top of type metadata yet. However it’s useful for writing your own validators or serialization frameworks.

完全不清楚attrs应该如何处理此元数据。 PEP 483/PEP 484 设计的核心部分是类型注释只不过是运行时的注释,不会影响值的类型或合法存储的位置;它们仅供静态类型检查器和其他独立于 Python.

运行的工具使用

特别是 Mypy(reference-standard 静态类型检查器)、一些 linters 和一些 IDE 应该将此标记为错误。如果他们还不支持 attrib 注释,他们几乎可以肯定正在处理它(因为它们大致等同于 3.7/PEP 557 dataclass 中的注释属性)。