[Python] python typing: overload vs TypeVar

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a best practice concerning the use of TypeVar and overload in python for functions that return the same type as the input? Consider these examples.

    Example 1. using TypeVar:

    from typing import TypeVar

    StrOrInt = TypeVar("StrOrInt", str, int)

    def return_same_type_typevar(x: StrOrInt) -> StrOrInt:
    if isinstance(x, str):
    # process str
    return x
    else:
    # process int
    return x


    Example 2, using overload:

    from typing import overload

    @overload
    def return_same_type_overload(x: str) -> str:
    ...

    @overload
    def return_same_type_overload(x: int) -> int:
    ...

    def return_same_type_overload(x):
    if isinstance(x, str):
    # process str
    return x
    else:
    # process int
    return x


    Are the two examples actually achieving the same? Is this use of overload discuraged here and should overload only be used when the return type is different from the input type? Or is it fine but overly verbose?

    Of course this is a trivial example. The code I am looking at would probably more take a pandas Series or DataFrame as input and not str and int.


    edit: updated example to show that there are different code paths for int and str

    Continue reading...

Compartilhe esta Página