繁体   English   中英

mypy - 类型提示新属性

[英]mypy - Type-hint new attributes

我经常使用dict对相关数据进行分组和命名空间。 两个缺点是:

  1. 无法对单个条目进行类型提示(例如x['s']: str = '' )。 稍后访问联合类型的值(例如x: dict[str, str | None] = {} )需要assert语句来取悦 mypy。
  2. 拼写条目冗长。 映射到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__中未定义的属性进行类型提示。

您需要声明某种具有已知字段或键的结构,然后使用它。 你有一大堆选择。 首先要考虑的事情(与您现有的尝试最相似)是TypedDictdataclass 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM