Typehints for Sized Iterable in Python

前端 未结 4 2084
佛祖请我去吃肉
佛祖请我去吃肉 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:27

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 09:46

    You should go with Sequence from typing if you plan to use only list or tuple and access its elements by index, like x[0]. Sequence is both Sized and Iterable, see here.

    0 讨论(0)
  • 2020-12-06 09:50

    Maybe you need a class like this?

    class MyArray:
      _array: list
    
      def as_tuple(self):
        return tuple(self._array)
    
      def as_list(self):
        return self._array
        
        # More Feature to implement
    
    
    0 讨论(0)
提交回复
热议问题