1

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.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Jayendra Parmar
  • 702
  • 12
  • 30

2 Answers2

1
from typing import TypeVar

T = TypeVar("T")

def concat(x1: T, x2: T) -> T:
    return x1 + x2
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Richard
  • 56,349
  • 34
  • 180
  • 251
  • 1
    Where’s the union in this example, I only see one type `T`? – Abhijit Sarkar Oct 09 '21 at 02:48
  • 1
    @AbhijitSarkar: The `T` takes any type and says the output is that same type. If you need `T` to be only for a subset of types you could say, eg, `TypeVar("T", int, str)`. – Richard Oct 09 '21 at 02:49
  • Thanks @richard it makes sense, I was not aware about TypeVar also takes additional arguments, the above example is clearly mentioned in to the python docs, I should have checked that before!!! – Jayendra Parmar Oct 09 '21 at 03:05
0

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

Andrew-Harelson
  • 1,022
  • 3
  • 11