title: How do I create a generic interface in Python?
body: <p>I want to create the equivalent of this in Python:</p>
  
  <pre class="lang-java prettyprint-override"><code>static class Event {}
  
  static class MyEvent extends Event {}
  
  interface Filter&lt;E extends Event&gt; {
      boolean filter(E event);
  }
  
  static class MyFilter implements Filter&lt;MyEvent&gt; {
      @Override public boolean filter(MyEvent event) {
          return true;
      }
  }
  </code></pre>
  
  <p>This is my attempt <a href="https://mypy-play.net/?mypy=latest&amp;python=3.8&amp;gist=54dca4dc19dbb1ed1b13a81d54621ad2" rel="noreferrer">(mypy-play)</a>:</p>
  
  <pre class="lang-python prettyprint-override"><code>from typing import TypeVar, Protocol
  
  class Event:
      pass
  
  class MyEvent(Event):
      pass
  
  E = TypeVar("E", bound=Event)
  
  class Filter(Protocol[E]):
      def filter(self, event: E) -&gt; bool:
          raise NotImplementedError
  
  class MyFilter(Filter):
      def filter(self, event: MyEvent) -&gt; bool:       # should be ok
          raise NotImplementedError
  
  class BadFilter(Filter):
      def filter(self, event: object) -&gt; bool:        # should fail
          raise NotImplementedError
  </code></pre>
  
  <p>...that fails with <code>main.py:11: error: Invariant type variable 'E' used in protocol where contravariant one is expected</code>. Unless I'm misunderstanding, Java seems to be fine with an invariant one, and this is my idea as well; I don't want various <code>Filter</code>s to be compatible with one another. In any case, slapping <code>contravariant=True</code> onto <code>T</code> <a href="https://mypy-play.net/?mypy=latest&amp;python=3.8&amp;gist=8e08b0d8806e91884981a1f9a65f36a2" rel="noreferrer">doesn't work either</a>. So,</p>
  
  <p>Why the protocol needs a contravariant variable? And, how do I make this Python code type check?</p>