Car*_*ate 18 python type-hinting python-3.x type-variables union-types
如果我想要一个可以是多种可能类型的类型,Unions 似乎是我表示的方式:
U = Union[int, str]
Run Code Online (Sandbox Code Playgroud)
U可以是一个int或一个str。
我注意到虽然TypeVars 允许可选的 var-arg 参数似乎也做同样的事情:
T = TypeVar("T", int, str)
Run Code Online (Sandbox Code Playgroud)
双方T并U似乎只被允许采取的类型str和int。
这两种方式之间有什么区别,何时应该首选?
Car*_*ate 28
T的类型必须在给定范围内的多次使用中保持一致,而U's 则不然。
对于Union用作函数参数的类型,参数和返回类型都可以不同:
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
Run Code Online (Sandbox Code Playgroud)
将其与TypeVar参数类型必须匹配的类似情况进行比较:
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
Run Code Online (Sandbox Code Playgroud)
因此,TypeVar如果允许多种类型,则使用 a ,但T单个范围内的不同用法必须相互匹配。Union如果允许多种类型,则使用 a ,但U给定范围内的不同用法不需要彼此匹配。
| 归档时间: |
|
| 查看次数: |
2227 次 |
| 最近记录: |