title: How to typehint a generic function?
body: <p>Say I want to define something in Python works exactly the same as the following function in Java:</p>
  
  <pre><code>public &lt;T&gt; void func(T a, T b):
       ...
  </code></pre>
  
  <p>This code simply means that <code>func</code> can take any <code>a</code> and <code>b</code> as input as long as they have the same data type.</p>
  
  <p>Python doesn't have an explicit type check itself, but now I am using mypy to check my code. My attempts are as follows:</p>
  
  <pre><code>T = TypeVar('T')
  
  def func(a: Generic[T], b: Generic[T]):
           ...
  func(1, 3)  # this should be a legal input since 1 and 3 are both int
  </code></pre>
  
  <p>and</p>
  
  <pre><code>T = TypeVar('T')
  
  class A(Generic[T]):
      pass
  
  def func(a: A[T], b: A[T]):
      ...
  func(1, 3)
  </code></pre>
  
  <p>However, mypy reports errors for both of them. Is there a way for us to define such generic function just as in Java to pass mypy check? I know for the purpose of sanity check for my code, I can also check whether <code>type(a)</code> equals <code>type(b)</code> inside the function, but this is not my purpose. I am specifically interested in my question as it is, i.e., how to define such a generic function to pass mypy check?</p>