【发布时间】:2018-08-31 20:22:02
【问题描述】:
我有一个函数在它的一个参数上使用len 函数并迭代参数。现在我可以选择是否使用Iterable 或Sized 来注释类型,但两者都会在mypy 中给出错误。
from typing import Sized, Iterable
def foo(some_thing: Iterable):
print(len(some_thing))
for part in some_thing:
print(part)
给予
error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized"
虽然
def foo(some_thing: Sized):
...
给予
error: Iterable expected
error: "Sized" has no attribute "__iter__"
由于没有Intersection 中讨论的this issue,因此我需要某种混合类。
from abc import ABCMeta
from typing import Sized, Iterable
class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta):
pass
def foo(some_thing: SizedIterable):
print(len(some_thing))
for part in some_thing:
print(part)
foo(['a', 'b', 'c'])
将foo 与list 一起使用时会出错。
error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"
这并不奇怪,因为:
>>> SizedIterable.__subclasscheck__(list)
False
所以我定义了一个__subclasshook__(参见docs)。
class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return Sized.__subclasscheck__(subclass) and Iterable.__subclasscheck__(subclass)
然后子类检查工作:
>>> SizedIterable.__subclasscheck__(list)
True
但是mypy 仍然抱怨我的list。
error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"
在使用len 函数和迭代我的参数时,如何使用类型提示?我认为投射foo(cast(SizedIterable, ['a', 'b', 'c'])) 不是一个好的解决方案。
【问题讨论】:
标签: python python-3.x type-hinting