相关疑难解决方法(0)

Python中大小可迭代的类型提示

我有一个函数,它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)
Run Code Online (Sandbox Code Playgroud)

error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized"
Run Code Online (Sandbox Code Playgroud)

def foo(some_thing: Sized):
...
Run Code Online (Sandbox Code Playgroud)

error: Iterable expected
error: "Sized" has no attribute "__iter__"
Run Code Online (Sandbox Code Playgroud)

由于本期没有Intersection讨论,我需要有一些混合类.

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', …
Run Code Online (Sandbox Code Playgroud)

python typing python-3.x

14
推荐指数
3
解决办法
1969
查看次数

标签 统计

python ×1

python-3.x ×1

typing ×1