Skip to content

Base class attribute type does not provide type context in subclass #4547

Closed

Description

@JukkaL

In this example there is an unnecessary message about needing a type annotation:

from typing import List

class A:
    x: List[str]

class B(A):
    x = []  # Need type annotation

Here we should we able to use the base class type for x as type context for the x initializer.

This is closely related to #3208.

Activity

  1. ilevkivskyi commented on Mar 6, 2019

    @ilevkivskyi
    Member

    #6511 provides another use case for this.

  2. ashb commented on Mar 6, 2019

    @ashb

    Minimal repro case:

    from typing import Iterable
    
    class A:
        a: Iterable[str] = ("a", )
    
    class B(A):
        a = ("a", "b")
    
    class C(B):
        a = ("a", "b", "c")

    And the error:

    a.py:10: error: Incompatible types in assignment (expression has type "Tuple[str, str, str]", base class "B" defined the type as "Tuple[str, str]")

    The error is reported on the assignment in C.

    I would have expected that B.a would have the same type as A.a since B.a doesn't have an explicit type.

    (This is the case from #6511 copied here in case it is useful)

  3. ilevkivskyi commented on May 3, 2019

    @ilevkivskyi
    Member

    (Raising priority to high since this keeps coming.)

  4. onlined commented on May 13, 2019

    @onlined
    Contributor

    This example from #6766 (comment), which is related to partial list type, doesn't give an error while it should:

    class A:
        x = ['a', 'b']
    
    class B(A):
        x = []
        x.append(2)
  5. ilevkivskyi commented on Aug 23, 2022

    @ilevkivskyi
    Member

    It looks like the situation is even worse here. Here we have no partial types and we still infer wrong type (the one that violates Liskov):

    from typing import List, Optional
    
    class B:
        x: List[Optional[int]]
    
    class C(B):
        x = [1]
    
    reveal_type(C().x)  # Revealed type is "builtins.list[builtins.int]"

    The problem is that we use supertype as type context when checking compatibility. But then again when storing the variable type we use empty context.

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