Skip to content

Incorrect "Attributes without a default cannot follow attributes with one" in dataclasses #6516

@reinhrst

Description

@reinhrst

Mypy incorrectly (in my understanding) complains about members in dataclasses having default values, even though many dataclasses.field assignments do not actually assign a default value.

I feel the correct behaviour should be to only detect an error if a field assignment that leads to a default value being assigned in the init method is followed by a default value.

This results (incorrectly) in an error:

import dataclasses

@dataclasses.dataclass
class A:
    x: int = dataclasses.field(metadata={"doc": "foo"})
    y: str

So does this:

import dataclasses

@dataclasses.dataclass
class A:
    x: int = dataclasses.field(init=False, default=1)
    y: str

Whereas this does not emit an error (where it should):

import dataclasses

@dataclasses.dataclass
class A:
    x: int = dataclasses.field(default=1)
    y: str = dataclasses.field(metadata={"doc": "foo"})

I understand that there may be quite some complexities to fix this correctly, but I would suggest in that case just removing this check altogether until it works correctly.

Tested on python 3.7.2 with mypy 0.670 and master, and python 3.6.6 with mypy 0.670

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongfalse-positivemypy gave an error on correct codepriority-1-normaltopic-pluginsThe plugin API and ideas for new plugins

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions