Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting unions

I have a function with two arguments:

def same_type_params(param1: Union[str, int], param2: Union[str, int]):
    pass

How do I constrain that the types of param1 and param2 are equal? i.e. either both str or both int

like image 520
Throckmorton Avatar asked Jan 17 '26 23:01

Throckmorton


1 Answers

Use a type variable:

from typing import TypeVar
T = TypeVar('T', str, int)
def same_type_params(param1: T, param2: T) -> None:
    pass
like image 159
juanpa.arrivillaga Avatar answered Jan 20 '26 11:01

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!