Mypy check with dataclass field and alias

Viewed 822

I'm struggling with mypy and dataclasses and especially with the field function.

Here is an example

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)

So far, so good. Mypy and python are happy

However, if I want to make a small helper around field to easily write my doc

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

Now I write my class like this:

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

And mypy throws

error: Attributes without a default cannot follow attributes with one

Both are equivalent, but it seems mypy have a special case around field (if I understand correctly)

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

So, my question is: is there a workaround to be able to write alias an for field?

Should I raise a bug on mypy?

0 Answers
Related