T的类型必须在给定范围内的多种用途之间保持一致,而
U的类型则不一致。
使用
Union类型作为函数参数时,参数以及返回类型都可以不同:
U = Union[int, str]def union_f(arg1: U, arg2: U) -> U: return arg1x = union_f(1, "b") # No error due to different typesx = union_f(1, 2) # Also no errorx = union_f("a", 2) # Also no errorx # And it can't tell in any of the cases if 'x' is an int or string将其与
TypeVar参数类型必须匹配的类似情况进行比较:
T = TypeVar("T", int, str)def typevar_f(arg1: T, arg2: T) -> T: return arg1y = typevar_f(1, "b") # "Expected type 'int' (matched generic type 'T'), got 'str' insteady = typevar_f("a", 2) # "Expected type 'str' (matched generic type 'T'), got 'int' insteady = typevar_f("a", "b") # No errory # It knows that 'y' is a stringy = typevar_f(1, 2) # No errory # It knows that 'y' is an int因此,
TypeVar如果允许使用多种类型,请使用a ,但
T单个作用域内的不同用法必须彼此匹配。
Union如果允许使用多种类型,则使用a
,但是
U在给定范围内的不同用法不需要相互匹配。



