Home > Blockchain >  Better typing hints in python?
Better typing hints in python?

Time:10-09

How can I be specific when I am using Union of types, let's say I have wrote a function which accepts either str or list and outputs whatever type was passed in, consider the following example

from typing import Union

def concat(x1: Union[str, list], x2: Union[str, list]) -> Union[str, list]:
    return x1   x2

I want the above example to be more specific like x1, x2 and returned value from the function all three must match the same types, but those types must be either str or list.

CodePudding user response:

from typing import TypeVar, Union

T = TypeVar("T")

def concat(x1: T, x2: T) -> T:
    return x1   x2

CodePudding user response:

The typing library has a @overload annotation that will do what you want. Note that it doesn't work exactly the same as overloading in other languages like java. You cannot create an overload with a different number of argument.

From the documentation:

@overload
def process(response: None) -> None:
    ...
@overload
def process(response: int) -> tuple[int, str]:
    ...
@overload
def process(response: bytes) -> str:
    ...
def process(response):
    <actual implementation>

https://docs.python.org/3/library/typing.html#typing.overload

  • Related