Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 暗示非发电机(非消耗性)可更换的类型_Python 3.x_Types_Type Hinting - Fatal编程技术网

Python 3.x 暗示非发电机(非消耗性)可更换的类型

Python 3.x 暗示非发电机(非消耗性)可更换的类型,python-3.x,types,type-hinting,Python 3.x,Types,Type Hinting,我想键入如下函数: from types import Iterable def func(thing: Iterable[str]) -> None: for i in range(10): for x in thing: do_thing(x) PyCharm将(正确地)让我不用向这个函数传递生成器,但我想以它不允许的方式键入hint,同时仍然接受其他iterable 使用Sequence[str]不是一个选项,像KeyView这样的

我想键入如下函数:

from types import Iterable

def func(thing: Iterable[str]) -> None:
    for i in range(10):
        for x in thing:
            do_thing(x)
PyCharm将(正确地)让我不用向这个函数传递生成器,但我想以它不允许的方式键入hint,同时仍然接受其他iterable

使用
Sequence[str]
不是一个选项,像KeyView这样的iterables不是序列,但我仍然希望能够包含它们

有人提到将
联合
序列
+
KeyView
一起使用,这会起作用,但我想知道是否有更优雅、更通用的解决方案

当然,我可以把
东西
转换成
列表
,但我更愿意正确地暗示这个函数类型


使用Python3.7

您不能使用联合来包含
序列
键视图
?我认为您必须使用Python3.5+@chrisz更新的问题来重新完善您的建议。我想,有一天,如果类型提示语法变得足够复杂,可以让您表达类型“一个
Iterable
,而不是一个
迭代器”,那么您可能最有可能大致表达这一点。在集合表示法中,这就是
Iterable\Iterator
——类型
Iterable
Iterator
的“差异”。不幸的是,虽然我们有
Union
s,但我们目前还没有任何类型的补码或交集,因此这是不可表达的。(请注意,即使像
Iterable\Iterator
这样的东西有一天会成为有效的Python,这可能是解决这个问题的一个不完美的解决方案,因为可以编写一个可消费的
Iterable
,但它不是一个
迭代器
。不过,这可能是一个罕见的坏主意,所以
Iterable\Iterator
,如果它变得可表达,可能就是您想要的。)