[Python] Is there a way to annotate a function with two generic arguments indicating that both...

Discussão em 'Python' iniciado por Stack, Abril 3, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to write a function accepting two arguments that are supposed to be compatible with the same base class:

    def example_function(base_object: RelatedType, desired_type: type[DesiredType]) -> DesiredType:
    ...


    where RelatedType and DesiredType should be generics bound to the same parent class (which is known only when the function is called with concrete arguments).

    I understand inheritance relationship cannot be enforced between different generics, i.e. something like:

    BaseType = TypeVar("BaseType")
    DerivedType = TypeVar("DerivedType", bound=BaseType)


    because a generic cannot be an upper bound.

    What is the correct way to provide meaningful type hints that convey the intended relationship?

    Continue reading...

Compartilhe esta Página