[Python] How to annotate a function that preserves type but applies a transformation to...

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say I have a function that takes only an argument and is guaranteed to return a value of the same type as the argument. Inside, depending on the specific type of the argument, it will apply some transformations or others.

    A minimal example could be something like this:

    from typing import TypeVar

    T = TypeVar("T")
    S = TypeVar('S', bound=str)

    def str_transform(s: S) -> S:
    return s

    def take_any_transform_only_str(obj: T) -> T:
    if isinstance(obj, str):
    return str_transform(obj)
    return obj


    It seems straightforward that take_any_transform_only_str will always return a value of the same type than the argument it was given. And yet, mypy (v1.15.0) complains with:

    test.py:11: error: Incompatible return value type (got "str", expected "T") [return-value]


    What would be the correct way to annotate this function?

    (Probably I could use typing.overload, but I'd very much prefer a solution based on type variables than having to manually annotate the different cases)

    Continue reading...

Compartilhe esta Página