Typehints for Sized Iterable in Python

前端 未结 4 2109
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 09:24

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

4条回答
  •  不知归路
    2020-12-06 09:41

    In the future Protocols will be introduced. They are already available through typing_extensions. See also PEP 544. Using Protocol the code above would be:

    from typing_extensions import Protocol
    
    
    class SizedIterable(Protocol):
    
        def __len__(self):
            pass
    
        def __iter__(self):
            pass
    
    
    def foo(some_thing: SizedIterable):
        print(len(some_thing))
        for part in some_thing:
            print(part)
    
    
    foo(['a', 'b', 'c'])
    

    mypy takes that code without complaining. But PyCharm is saying

    Expected type 'SizedIterable', got 'List[str]'

    about the last line.

提交回复
热议问题