[英]How do I type hint a question that returns a zip object?
I've got a function that takes an arbitrary amount of lists (or any iterables, for that matter) and sorts them as one.我有一个 function 需要任意数量的列表(或任何可迭代的,就此而言)并将它们排序为一个。 The code looks like this:
代码如下所示:
def sort_as_one(*args):
return zip(*sorted(zip(*args)))
def main():
list1 = [3, 1, 2, 4]
list2 = ["a", "b", "d", "e"]
list3 = [True, False, True, False]
result = sort_as_one(list1, list2, list3)
# <zip object at ...>
print(result)
list1, list2, list3 = result
print(list1, list2, list3)
if __name__ == "__main__":
main()
How can I accurately type hint the function output?如何准确键入提示 function output?
A zip
object is an iterator - it follows the iterator protocol. zip
object 是一个迭代器——它遵循迭代器协议。 Idiomatically, you would probably just typing hint it as such.习惯上,您可能只是这样输入提示。 In this case, you want to type hint it as a generic using a type variable:
在这种情况下,您希望使用类型变量将其作为泛型类型提示:
import typing
T = typing.TypeVar("T")
def sort_as_one(*args: T) -> typing.Iterator[T]:
return zip(*sorted(zip(*args)))
Note, if you are using variadic arguments, you have to only accept a single type.请注意,如果您使用可变参数 arguments,您必须只接受一个类型。 In this case, the best you can probably do in your case is use
Any
instead of T
.在这种情况下,您可以做的最好的事情是使用
Any
而不是T
。 But you should consider using only a function like the above in your code if you want to be able to use it with static type checkers.但是,如果您希望能够将 function 与 static 类型检查器一起使用,则应考虑仅在代码中使用上述 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.