Skip to content

Initializer not checked against declared type when annotating using self.x #7398

Closed
@sotte

Description

@sotte

mypy accepts instance variables that are instantiated as None even though the type indicates int. This is not the case for equivalent dataclasses. I'm not sure if this is a bug or intended behavior.

Here is a minimal example:

from dataclasses import dataclass, field


class Foo:
    def __init__(self):
        self.bar: int = None


@dataclass
class Foo2:
    bar: int = None
    bar2: int = field(default=None)

This is how I check the fiel: mypy mypy_demo.py.

Here the resulting error msgs:

mypy_demo.py:11: error: Incompatible types in assignment (expression has type "None", variable has type "int")
mypy_demo.py:12: error: Incompatible types in assignment (expression has type "None", variable has type "int")

I did not find anything helpful in the dataclass section: https://mypy.readthedocs.io/en/latest/additional_features.html#dataclasses

I'm testing with Mypy version 0.701.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions