python-attrs / python-attrs/attrs

Inheritance breaks mypy type checking with optional attributes if Generics are involved

Open
#1,028 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Waiting for Mypy
Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

Inheritance breaks mypy type checking with optional attributes if Generics are involved:

from typing import Generic, Optional, TypeVar

import attr

T = TypeVar("T")


@attr.mutable()
class Parent(Generic[T]): # Removing `Generic` here and `[float]` below doesn't show `mypy` issues anymore
    run_type: Optional[int] = None


@attr.mutable()
class Child(Parent[float]):
    pass


Parent(
    run_type =None,
)

Child(
    run_type =None, # error: Argument "run_type" to "Child" has incompatible type "None"; expected "int"  [arg-type]
)

There is an error displayed which is wrong. Doing the same without any Generic involved works as expected.

Not quite sure if this is a mypy issue or an attrs typing issue.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python reproducer with mypy and compare the Parent and Child constructor diagnostics. Trace whether the incorrect inference comes from attrs-generated typing or mypy's generic inheritance handling; done means the reproducer accepts Child(run_type=None) without regressing the non-generic case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.