python / python/mypy

Inherited, overridden attribute type reverted to the top parent class type

Open
#7,394 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-inheritance
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

The issue type is probably quite bad, but example should quickly clear things up:

class A:
    attr = None


class B(A):
    attr: str  # type: ignore


class C1(B):
    attr = "test"


class C2(B):
    pass


class D(C2):
    attr = "test"

mypy test.py outputs:

test.py:18: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "None")

where line 18 is the last line of above example

As to why I do attr: str # type: ignore - in a nutshell, in my case A class comes from external source and they botched type hints there so I try to fix them in B. Not sure if it should have worked for C1, but if it did I see it breaking in D as a bug due mypy not being consistent, but then again maybe there is a good reason for it?.

Tested with mypy 0.720

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 inheritance example with mypy 0.720 and compare the diagnostics for C1 and D. Trace the type resolution for inherited and overridden attributes, then confirm the resulting behavior is consistent with the intended semantics described in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
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.