[英]mypy - Type-hint new attributes
我经常使用dict
对相关数据进行分组和命名空间。 两个缺点是:
x['s']: str = ''
)。 稍后访问联合类型的值(例如x: dict[str, str | None] = {}
)需要assert
语句来取悦 mypy。str
键的值需要四个额外的字符(即['']
); 属性只需要一个(即.
)。 我考虑types.SimpleNamespace
。 但是,与类一样,我遇到了这个mypy错误:
import types
x = types.SimpleNamespace()
x.s: str = ''
# 3 col 2 error| Type cannot be declared in assignment to non-self attribute [python/mypy]
dict
不同,与collections.namedtuple
不同,我需要可变性。无法对 class 主体或__init__
中未定义的属性进行类型提示。
您需要声明某种具有已知字段或键的结构,然后使用它。 你有一大堆选择。 首先要考虑的事情(与您现有的尝试最相似)是TypedDict
和dataclass
。 TypedDict
不进行运行时验证,只是代码执行期间的普通字典(不适用键/值限制)。 dataclass
将为您创建一个__init__
,但您稍后可以设置任何属性(没有注释,对mypy
不可见)。 使用dataclass(slots=True)
,这是不可能的。
让我举几个例子:
from typing import TypedDict
class MyStructure(TypedDict):
foo: str
data: MyStructure = {'foo': 'bar'}
reveal_type(data['foo']) # N: revealed type is "builtins.str"
data['foo'] = 'baz' # OK, mutable
data['foo'] = 1 # E: Value of "foo" has incompatible type "int"; expected "str" [typeddict-item]
data['bar'] # E: TypedDict "MyStructure" has no key "bar" [typeddict-item]
# Second option
from dataclasses import dataclass
@dataclass
class MyStructure2:
foo: str
data2 = MyStructure2(foo='bar')
reveal_type(data2.foo) # N: Revealed type is "builtins.str"
data2.foo = 'baz' # OK, mutable
data2.foo = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
data2.bar # E: "MyStructure2" has no attribute "bar" [attr-defined]
这是游乐场链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.