使用dataclass字段和别名进行Mypy检查

2024-04-20 07:53:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力处理mypy和dataclass,尤其是field函数

这里有一个例子

from dataclasses import field, dataclass

@dataclass
class C:
    some_int: int
    some_str: str = field(metadata={"doc": "foo"})
    another_int: int

c = C(42, "bla", 43)

到目前为止,一切顺利。Mypy和python很高兴

但是,如果我想在field周围创建一个小助手,以便轻松编写文档

def doc(documentation: str):
    return field(metadata={"doc": documentation})

现在我这样写我的课堂:

@dataclass
class C:
    some_int: int
    some_str: str = doc("foo")
    another_int: int

还有mypy投的球

error: Attributes without a default cannot follow attributes with one

两者都是等价的,但似乎mypy在field附近有一个特例(如果我理解正确的话)

https://github.com/python/mypy/blob/v0.790/mypy/plugins/dataclasses.py#L359

因此,我的问题是:是否有一种变通方法可以为field编写别名

我应该在mypy上引起一个bug吗


Tags: 函数fielddocfoodocumentationanothersomeclass