title: Subclassing Sequence with proper type hints in Python
body: <p>I'm trying to implement a kind of custom sequence class in Python:</p>
  
  <pre><code>from typing import Sequence, TypeVar, List
  
  T = TypeVar('T')
  
  class MySequence(Sequence[T]):
      def __init__(self):
          self._container: Sequence[T] = []
      def __getitem__(self, idx):
          return self._container[idx]
      def __len__(self):
          return len(self._container)
  </code></pre>
  
  <p>Now I want to check that <em>mypy</em> is aware that elements of <code>MySequence</code> are items of type <code>T</code>:</p>
  
  <pre><code>foo: MySequence[str] = MySequence()
  reveal_type(foo[0])
  # Revealed type is 'Any'
  </code></pre>
  
  <p>So it fails: <em>mypy</em> knows nothing about items of <code>foo</code>. The same example for ordinary <code>Sequence</code> works:</p>
  
  <pre><code>bar: Sequence[str] = []
  reveal_type(bar[0])
  # Revealed type is 'builtins.str*'
  </code></pre>
  
  <p>If I'm trying to add type annotations to <code>__getitem__</code> implementation, I have another error:</p>
  
  <pre><code>def __getitem__(self, idx) -&gt; T:
  # Signature of "__getitem__" incompatible with supertype "Sequence"
  </code></pre>
  
  <p>I also tried</p>
  
  <pre><code>def __getitem__(self, idx) -&gt; Union[T, Sequence[T]]:
  </code></pre>
  
  <p>as <code>idx</code> can be a slice and in that case my code will return a sequence instead of one element. It fails either with the same message.</p>
  
  <p>As discussed in <a href="https://stackoverflow.com/questions/46685165/mypy-signature-of-getitem-incompatible-with-supertype-sequence">my previous question</a>, there is an <a href="https://github.com/python/mypy/issues/1237" rel="noreferrer">open discussion</a> on issues like that.</p>
  
  <p>However, I still wonder, is it possible to create custom sequence types that allow <em>mypy</em> to extract information about the type of its items, like in my example?</p>