[Python] Using a Python Protocol to type hint a specific implementation of a class that...

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have some code that looks approximately like this

    from typing import Tuple

    class Parent:
    ...

    class Child1(Parent):
    def method1(self): ...

    class Child2(Parent):
    def method2(self): ...

    class Container:
    def __init__(self, attr: Tuple[Parent, ...]):
    self.attr = attr


    and some legacy code that only accepts a Container argument when attr consists of elements of type Child_1, e.g.

    def func(container_argument):
    for e in container_argument.attr:
    e.method_1()


    I assumed that I could define a Protocol to structurally type-hint func, such that Containers that only contain instances of Child1 can be accepted as an argument. For example,

    from typing import Protocol

    class ContainerChild1Proto(Protocol):
    attr: Tuple[Child1, ...]

    def func(container_argument: ContainerChild1Proto):
    for e in container_argument.attr:
    e.method_1()

    child1_only_container = Container((Child1(),))
    mixed_container = Container((Child1(), Child2()))

    func(child1_only_container) # hopefully passes
    func(mixed_container) # hopefully fails



    My hope was that a static type-checker would be able to recognise that child1_only_container matches the protocol, and that mixed_container doesn't, but pytype seems to just see that child1_only_container is of type Container which doesn't necessarily match ContainerChild1Proto and hence flags it as an error.

    Continue reading...

Compartilhe esta Página