Skip to content

Incompatible definition of generic field on multiple base classes #9031

Closed

Description

@dn-kialo

[BUG] Edited for a clearer example
Given this code:

# mypy version 0.770
from typing import Generic, TypeVar

T = TypeVar("T", int, str)

class A:
  foo: int

class B(Generic[T]):
  foo: T

class C(B[int], A):
  pass

reveal_type(A().foo)
reveal_type(B().foo)
reveal_type(C().foo)

I get this output:

example.py:11: error: Definition of "foo" in base class "B" is incompatible with definition in base class "A"
example.py:14: note: Revealed type is 'builtins.int'
example.py:15: note: Revealed type is 'builtins.int*'
example.py:16: note: Revealed type is 'builtins.int*'

I couldn't find what builtins.int*. The code makes sense though, right?

Activity

  1. ilevkivskyi commented on Jul 3, 2020

    @ilevkivskyi
    Member

    Yeah, this is a mypy bug. Likely related to #7724

  2. headtr1ck commented on Jun 17, 2022

    @headtr1ck

    Still happening with mypy 0.960 :(
    Although, now without "*" in the revealed types.

  3. adamchainz commented on Nov 11, 2022

    @adamchainz
    Sponsor

    I think I just encountered a modified version of this in django-stubs: typeddjango/django-stubs#1227 . Due to the structure of the classes we are trying to type, the attribute is defined as generic in both base classes, and passed as a type parameter to each:

    from typing import Generic, TypeVar
    
    T = TypeVar("T", int, str)
    
    class A(Generic[T]):
      foo: T
    
    class B(Generic[T]):
      foo: T
    
    class C(Generic[T], B[T], A[T]):
      pass
    
    c: C[int] = C()
    
    reveal_type(A().foo)
    reveal_type(B().foo)
    reveal_type(c.foo)
  4. tonysyu commented on Dec 20, 2022

    @tonysyu

    I just ran into the same issue. I don't see it explicitly mentioned above, but one workaround is to explicitly type the attribute in the concrete class (if that's an option; i.e. if the type is resolved in the class definition rather than the variable declaration); e.g.

    from typing import Generic, TypeVar
    
    T = TypeVar('T')
    
    class A(Generic[T]):
        value: T
    
    class B(Generic[T]):
        value: T
    
    class C(A[int], B[int]):
        value: int
  5. added a commit that references this issue on Jan 11, 2025
    d86b1e5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions