使用列表/元组/等.从键入 vs 直接引用类型为列表/元组/等 [英] Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc
问题描述
typing
模块中使用List
、Tuple
等有什么区别:
What's the difference of using List
, Tuple
, etc. from typing
module:
from typing import Tuple
def f(points: Tuple):
return map(do_stuff, points)
与直接引用 Python 的类型相反:
As opposed to referring to Python's types directly:
def f(points: tuple):
return map(do_stuff, points)
我什么时候应该使用一个?
And when should I use one over the other?
推荐答案
typing.Tuple
和 typing.List
是 泛型;这意味着您可以指定他们的内容必须是什么类型:
typing.Tuple
and typing.List
are Generic types; this means you can specify what type their contents must be:
def f(points: Tuple[float, float]):
return map(do_stuff, points)
这指定传入的元组必须包含两个 float
值.你不能用内置的 tuple
类型做到这一点.
This specifies that the tuple passed in must contain two float
values. You can't do this with the built-in tuple
type.
typing.Tuple
这里的特殊之处在于它允许您指定特定数量的预期元素和每个位置的类型.如果未设置长度且类型应重复,则使用省略号:Tuple[float, ...]
描述了一个带有 float的可变长度
tuple
代码>s.
typing.Tuple
is special here in that it lets you specify a specific number of elements expected and the type of each position. Use ellipsis if the length is not set and the type should be repeated: Tuple[float, ...]
describes a variable-length tuple
with float
s.
对于typing.List
和其他序列类型你一般只为所有元素指定类型;List[str]
是任意大小的字符串列表.请注意,函数应优先采用 typing.Sequence
作为参数,typing.List
通常只用于返回类型;一般来说,大多数函数都可以接受任何序列并且只进行迭代,但是当您返回 list
时,您实际上是在返回特定的、可变的序列类型.
For typing.List
and other sequence types you generally only specify the type for all elements; List[str]
is a list of strings, of any size. Note that functions should preferentially take typing.Sequence
as arguments and typing.List
is typically only used for return types; generally speaking most functions would take any sequence and only iterate, but when you return a list
, you really are returning a specific, mutable sequence type.
即使您当前没有限制内容,您也应该始终选择 typing
泛型.稍后使用泛型类型添加该约束会更容易,因为产生的更改会更小.
You should always pick the typing
generics even when you are not currently restricting the contents. It is easier to add that constraint later with a generic type as the resulting change will be smaller.
这篇关于使用列表/元组/等.从键入 vs 直接引用类型为列表/元组/等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!