约束的TypeVar和Union之间有什么区别? [英] What's the difference between a constrained TypeVar and a Union?
问题描述
如果我想要一个可以表示多种可能类型的类型,那么Union
似乎就是我的表达方式:
If I want to have a type that can represent multiple possible types, Union
s seem to be how I represent that:
U = Union[int, str]
U
可以是int
或str
.
我注意到,尽管TypeVar
允许可选的var-arg参数,但它们似乎也做同样的事情:
I noticed though that TypeVar
s allow for optional var-arg arguments that also seem to do the same thing:
T = TypeVar("T", int, str)
T
和U
似乎都只能采用str
和int
类型.
Both T
and U
seem to only be allowed to take on the types str
and int
.
这两种方式之间有什么区别,什么时候应该优先使用?
What are the differences between these two ways, and when should each be preferred?
推荐答案
T
's type must be consistent across multiple uses within a given scope, while U
's does not.
使用Union
类型作为函数参数时,参数以及返回类型都可以不同:
With a Union
type used as function parameters, the arguments as well as the return type can all be different:
U = Union[int, str]
def union_f(arg1: U, arg2: U) -> U:
return arg1
x = union_f(1, "b") # No error due to different types
x = union_f(1, 2) # Also no error
x = union_f("a", 2) # Also no error
x # And it can't tell in any of the cases if 'x' is an int or string
将其与参数类型必须匹配的TypeVar
进行比较:
Compare that to a similar case with a TypeVar
where the argument types must match:
T = TypeVar("T", int, str)
def typevar_f(arg1: T, arg2: T) -> T:
return arg1
y = typevar_f(1, "b") # "Expected type 'int' (matched generic type 'T'), got 'str' instead
y = typevar_f("a", 2) # "Expected type 'str' (matched generic type 'T'), got 'int' instead
y = typevar_f("a", "b") # No error
y # It knows that 'y' is a string
y = typevar_f(1, 2) # No error
y # It knows that 'y' is an int
因此,如果允许多种类型,请使用TypeVar
,但是在单个作用域内T
的不同用法必须彼此匹配.如果允许使用多种类型的U
,请使用Union
,但是在给定范围内的不同用法不需要相互匹配.
So, use a TypeVar
if multiple types are allowed, but different usages of T
within a single scope must match each other. Use a Union
if multiple types of U
are allowed, but different usages within a given scope don't need to match each other.
这篇关于约束的TypeVar和Union之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!