title: User defined generic types and collections.abc
body: <p>I have a Python package that defines a variety of collections based on the ABCs provided by <em>collections.abc</em> (<em>Mapping</em>, <em>Sequence</em>, etc). I want to take advantage of the type hinting facilities introduced in Python 3.5, but I'm having doubts as to what would be the best way to go about it.</p>
  
  <p>Lets take one of these classes as an example; until now, I had something
  resembling this:</p>
  
  <pre><code>from collections.abc import Mapping
  
  class MyMapping(Mapping):
      ...
  </code></pre>
  
  <p>To turn this into a generic type, the <a href="https://www.python.org/dev/peps/pep-0484/#arbitrary-generic-types-as-base-classes">documentation</a> suggests doing something like this:</p>
  
  <pre><code>from typing import TypeVar, Hashable, Mapping
  
  K = TypeVar("K", bound=Hashable)
  V = TypeVar("V")
  
  class MyMapping(Mapping[K, V]):
      ...
  </code></pre>
  
  <p>But this poses two problems:</p>
  
  <ul>
  <li><p>The class looses all the mixin methods from <em>collections.abc.Mapping</em>. I could deal with this implementing them myself, but that would defeat part of the purpose of using ABCs in the first place.</p></li>
  <li><p><code>isinstance(MyMapping(), collections.abc.Mapping)</code> returns False. Also, trying to call <code>collections.abc.Mapping.register(MyMapping)</code> to work around this raises a <em>RuntimeError</em> ("Refusing to create an inheritance cycle").</p></li>
  </ul>
  
  <p>My first attempt to solve these problems was to go back to extending <em>collections.abc.Mapping</em>:</p>
  
  <pre><code>from typing import TypeVar, Hashable
  from collections.abc import Mapping
  
  K = TypeVar("K", bound=Hashable)
  V = TypeVar("V")
  
  class MyMapping(Mapping[K, V]):
      ...
  </code></pre>
  
  <p>But that doesn't work, as <em>collections.abc.Mapping</em> is not a generic type and does not support the subscription operator. So I tried this:</p>
  
  <pre><code>from typing import TypeVar, Hashable, Mapping
  from collections.abc import Mapping as MappingABC
  
  K = TypeVar("K", bound=Hashable)
  V = TypeVar("V")
  
  class MyMapping(MappingABC, Mapping[K, V]):
      ...
  </code></pre>
  
  <p>But this smells fishy. The imports and aliasing are cumbersome, the resulting class has a tortuous MRO, and the mix-in methods provided by the ABC won't have typing information...</p>
  
  <p>So what is the preferred way to declare a custom generic type based on a collection ABC?</p>