[Python] How can I annotate a function that takes a tuple of types and returns an object of...

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

  1. Stack

    Stack Membro Participativo

    I want to annotate a function that essentially does this:

    def safe_convert(value: Any, allowed_types: tuple):
    if isinstance(value, allowed_types):
    return value
    raise TypeError()


    Now, my intention is for allowed_types to be a tuple of type objects, and to tell the type checker that the result is a Union of those types, but I can't figure out how to do that. My closest attempt is to write something like this:

    def safe_convert[*Ts](value: Any, allowed_types: tuple[*type[Ts]]) -> Union[*Ts]:
    ...


    But this produces an error: **error: "type[Ts]" cannot be unpacked (must be tuple or TypeVarTuple) [valid-type]**

    For reference, the single argument version works just fine:

    def safe_convert_single[T](value: Any, allowed_type: type[T]) -> T:
    if isinstance(value, allowed_type):
    return value
    raise TypeError()


    Any ideas? I'm really struggling here.

    Continue reading...

Compartilhe esta Página