Skip to content

list of subclasses cannot be assigned to list of superclass #130

@sarisia

Description

@sarisia

Describe the bug
I have a Base class and a Child class derived from Base class.
When I try to assign a list of Child instances to List[Base],
the list of Child is recognized as List[Child] and get warning.

To Reproduce
Reproducible code:

from typing import List

class Base():
    pass

class Child(Base):
    pass

class AnotherChild(Base):
    pass


success: List[Base] = [Child(), AnotherChild()]

fail: List[Base] = [Child(), Child()]
fail2: List[Base] = [AnotherChild(), AnotherChild()]

In the code above, I got

Expression of type 'list[Child]' cannot be assigned to declared type 'List[Base]'pyright

for fail and

Expression of type 'list[AnotherChild]' cannot be assigned to declared type 'List[Base]'pyright

for fail2.

Expected behavior
Both Child and AnotherChild is inherited from Base so
List[Child] and List[AnotherChild] should be able to be assigned to List[Base]
without warnings.

Screenshots or Code
pyrightissue

VS Code extension or command-line
pyright as a VS Code extension
Pyright 1.0.29

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions