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

蓝咒 提交于 2019-12-01 17:30:59

The syntax is indeed valid. But the generic type annotation objects added by PEP 484 are not in the builtins namespace, but in the typing module.

So, you need to do what all of the examples in the attrs docs you linked, and PEP 484, PEP 483, PEP 526, and the typing docs do:

from typing import List

Also, note that this is just an annotation. You can still write c = C(x=[], y=[1.0]) and you won't get a TypeError. As the docs you linked say:

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.

It's not at all clear what attrs should do with this metadata. It's a central part of the design of PEP 483/PEP 484 that type annotations are nothing more than annotations are runtime, and do not affect the types of values or what's legal to store where; they're only there to be used by static type checkers and other tools that runs separately from Python.

In particular, Mypy (the reference-standard static type checker), some linters, and some IDEs should flag this as an error. If they don't support attrib annotations yet, they're almost certainly working on it (since they're roughly equivalent to annotated attributes in 3.7/PEP 557 dataclass).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!