Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

Typehints for Sized Iterable in Python

I have a function that uses the len function on one of it's parameters and iterates over the parameter. Now I can choose whether to annotate the type with Iterable or with Sized, but both gives errors in mypy.

from typing import Sized, Iterable


def foo(some_thing: Iterable):
    print(len(some_thing))
    for part in some_thing:
        print(part)

Gives

error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized"

While

def foo(some_thing: Sized):
...

Gives

error: Iterable expected
error: "Sized" has no attribute "__iter__"

Since there is no Intersection as discussed in this issue I need to have some kind of mixed class.

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'])

This gives an error when using foo with a list.

error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"

This is not too surprising since:

>>> SizedIterable.__subclasscheck__(list)
False

So I defined a __subclasshook__ (see docs).

class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta):

    @classmethod
    def __subclasshook__(cls, subclass):
        return Sized.__subclasscheck__(subclass) and Iterable.__subclasscheck__(subclass)

Then the subclass check works:

>>> SizedIterable.__subclasscheck__(list)
True

But mypy still complains about my list.

error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"

How can I use type hints when using both the len function and iterate over my parameter? I think casting foo(cast(SizedIterable, ['a', 'b', 'c'])) is not a good solution.

question from:https://stackoverflow.com/questions/49427944/typehints-for-sized-iterable-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting from Python3.6 there's a new type called Collection. See here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...