python / python/mypy

Class variable in multiple base classes incompatible

Open
#17,079 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I'm getting a mypy error when I inherit from multiple base classes which define the same class variable.

A minimal script looks like:

class Obj:
    ...

class Left(Obj):
    ...

class Right(Obj):
    ...

class A:
    val: Obj

class B(A):
    val = Left()

class C(A):
    val = Right()

class D(B, C):
    ...

The error I get is:

Definition of "val" in base class "B" is incompatible with definition in base class "C"  [misc]

I was expecting there to be no error here. The following script works, for instance:

class Obj:
    ...

class Left(Obj):
    ...

class Right(Obj):
    ...

val: Obj
val = Left()
val = Right()

I can avoid the error by changing the definitions of B and C to:

class B(A):
    val: Obj = Left()

class C(A):
    val: Obj = Right()

But this seems redundant.

Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: None
  • Python version used: 3.11

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 minimal multiple-inheritance script with mypy 1.9.0 and compare it with the working module-level assignment example. Trace the handling of inherited class-variable definitions and confirm that compatible subclass assignments no longer produce the reported [misc] error, while the existing annotation workaround remains valid.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.