如何提示 python3.6 参数必须有大小且可迭代?
How to hint python3.6 that parameter must be sized and iterable both?
我有一个函数要求参数同时是 Sized 和 Iterable。
def foo(items):
print(len(items))
for i in item:
print(i)
我认为我可以使用 python3.5+ 中的标准 typing
模块并编写:
from typing import Collection, Any
def foo(items: Collection[Any]):
print(len(items))
for i in item:
print(i)
foo([1, 2, 3])
# PyCharm warns: Expected type 'Collection', got 'List[int]' instead.
Collection 看起来像我需要的:class typing.Collection(Sized, Iterable[T_co], Container[T_co])
为什么会出现警告?
我应该如何将参数提示为 Iterable 和 Sized?
Collection
was only introduced in 3.6;很有可能,您的 PyCharm 版本还不能识别它。
在 3.5 中没有内置的描述大小的、可迭代的容器,所以你不能在 3.5 中使用这个注解,至少,不能不写你自己的 typing
类型,PyCharm可能会或可能不会。
让 Python 3.5 快乐的一个肮脏的修复是使用 Union[Sized, Iterable[Any]]
.
它很脏,因为使用此类型注释表示它应该是大小或可迭代的,而不是大小和可迭代的。
当前的 Pycharm (2018.1) 接受这个,它运行。
更新:
我找到了一种在 Python 版本 < 3.6 中使用 Collections
的方法。
3.6 之前的 Sequence
基本上就是 3.6 中的 Collection
(参见 here and here). In 3.6 a Sequence
is basically a reversible Collection
(see here),这给了我一些问题,因为 python set
不是一个序列(它是不可逆的)所以我用以下导入代码修补它:
if sys.version_info >= (3, 6):
from typing import Collection
else:
from typing import Sequence, TypeVar
T = TypeVar('T')
Collection = Sequence[T]
我有一个函数要求参数同时是 Sized 和 Iterable。
def foo(items):
print(len(items))
for i in item:
print(i)
我认为我可以使用 python3.5+ 中的标准 typing
模块并编写:
from typing import Collection, Any
def foo(items: Collection[Any]):
print(len(items))
for i in item:
print(i)
foo([1, 2, 3])
# PyCharm warns: Expected type 'Collection', got 'List[int]' instead.
Collection 看起来像我需要的:class typing.Collection(Sized, Iterable[T_co], Container[T_co])
为什么会出现警告?
我应该如何将参数提示为 Iterable 和 Sized?
Collection
was only introduced in 3.6;很有可能,您的 PyCharm 版本还不能识别它。
在 3.5 中没有内置的描述大小的、可迭代的容器,所以你不能在 3.5 中使用这个注解,至少,不能不写你自己的 typing
类型,PyCharm可能会或可能不会。
让 Python 3.5 快乐的一个肮脏的修复是使用 Union[Sized, Iterable[Any]]
.
它很脏,因为使用此类型注释表示它应该是大小或可迭代的,而不是大小和可迭代的。 当前的 Pycharm (2018.1) 接受这个,它运行。
更新:
我找到了一种在 Python 版本 < 3.6 中使用 Collections
的方法。
3.6 之前的 Sequence
基本上就是 3.6 中的 Collection
(参见 here and here). In 3.6 a Sequence
is basically a reversible Collection
(see here),这给了我一些问题,因为 python set
不是一个序列(它是不可逆的)所以我用以下导入代码修补它:
if sys.version_info >= (3, 6):
from typing import Collection
else:
from typing import Sequence, TypeVar
T = TypeVar('T')
Collection = Sequence[T]