[Python] Sequence of child classes requires empty instantiation

Discussão em 'Python' iniciado por Stack, Agosto 29, 2025.

  1. Stack

    Stack Membro Participativo

    Consider this:

    class Foo(): ...
    class Child1(Foo): ...
    class Child2(Foo): ...

    my_list: list[Foo] = [Child1()]
    my_list.append(Child2())


    All good, no typing errors!

    Now consider this:

    def list_of_child1() -> list[Child1]:
    return [Child1(), Child1()]

    my_list2: list[Foo] = list_of_child1()


    Type "list[Child1]" is not assignable to declared type "list[Foo]"
    "list[Child1]" is not assignable to "list[Foo]"
    Type parameter "_T@list" is invariant, but "Child1" is not the same as "Foo"
    Consider switching from "list" to "Sequence" which is covariant


    Which makes a lot of sense and we can use Sequence:

    my_list3: Sequence[Foo] = list_of_child1()
    my_list3.append(Child2())


    However this raises:

    Argument of type "Child2" cannot be assigned to parameter "object" of type "Child1" in function "append"
    "Child2" is not assignable to "Child1"


    Somehow the sequence overwrites its initial declaration and gets casted to list[Child1]?

    But this works?

    my_list4: Sequence[Foo] = []
    my_list4.extend(list_of_child1())
    my_list4.append(Child2())

    Continue reading...

Compartilhe esta Página