Zelta
Zelta

Reputation: 764

Tell pycharm to infer types from superclass' methods?

I'm writing a library in which I have a class that should be subclassed by users. I've added typehints to that class hoping that they will affect subclasses as well so that users don't have to add type hints themselves.

However, it does not work:

# Class from the library
class A:
    def a(self, d: dict):
        raise NotImplementedError()


# User-defined subclass
class B(A):
    def a(self, d):
        ...

Infered type of variable d in B.d is Any, but I want it to be dict. Is there any way I can tell pycharm that it's dict without writing another typehint? Is there any common practices for such cases?

Upvotes: 1

Views: 210

Answers (1)

Corley Brigman
Corley Brigman

Reputation: 12391

This isn't C++, where the superclass defines a signature and subclasses implement it. in python, everything is explicit... it would be bad form for A.a and B.a to have different signatures, and have a completely different list of arguments, but nothing actually disallows it:

In [7]: class A(object):
   ...:     def a(self, x, y, z):
   ...:         print (x, y, z)
   ...:         

In [8]: class B(A):
   ...:     def a(self, m, n, o):
   ...:         print (m + n + o)
   ...:         

In [9]: b = B()
In [10]: b.a(1,2,3)
6
In [11]: a = A()
In [12]: a.a(1,2,3)
1 2 3

Now, in the real world, if you actually did anything like this with classes you expect people to use, they would rightfully scream and kick you out of the project... a predictable API is a central part of inheritance.

This is possible because unlike C++, where function lookup is done by signature for polymorphism (e.g. you can write int f(int a); and int f(float f);, which are two separate functions with the same name, and the compiler knows which one to call by what argument types the caller uses), Python function lookup is only on the name.

But even though assuming the signature is the same as the superclass is technically wrong, as PyCharm would have a difficult time proving that you really did mean the same thing, in practice that is how most people would use it, so an option to do that would be useful.

One last thing... today, function annotations are just 'fyi', but there are projects that are attempting to actually use them for things... decorators that will check the argument types before calling the function, for instance. Even if PyCharm can infer the annotations, the code itself won't when it runs, and if you want them for any of that functionality, you may have to go ahead and include them explicitly.

Upvotes: 2

Related Questions