Skip to content

List[subclass] is incompatible with List[superclass] #2984

Closed
@Stiivi

Description

@Stiivi

When a function that is accepting a list of a base class (for example class Base) is passed and argument which is a list of subclass instances of the base class (for example Thing(Base)) mypy complains about incompatible type: Error: Argument 1 to "function" has incompatible type List[Thing]; expected List[Base].

Wrapping the argument with a cast to a list of the base class passes.

Code example:

from typing import List, cast

class Base:
    pass

class Thing(Base):
    pass

def function(arg: List[Base]) -> None:
    pass

things:List[Thing] = [Thing()]

# Error: Argument 1 to "function" has incompatible type List[Thing]; expected List[Base]
function(things)

# Passes
function(cast(List[Base], things))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions