简体   繁体   中英

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? ie either both str or both int

Use a type variable :

from typing import TypeVar
T = TypeVar('T', str, int)
def same_type_params(param1: T, param2: T) -> None:
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM