1
votes

Is it possible to propagate type hinting to overridding methods?

Say, I have the following classes:

class Student:
    def study():
        pass

class Option:
    self.option_value

class BaseChoice:
   def make_choice(self, student, options):
        """
        :type student: Student
        :type options: list[Option]
        """

class RationalChoice(BaseChoice):
   def make_choice(self, student, options):
        pass

When I'm inside RationalChoice.make_choice pycharm does not suggest autocomplete for options properties/methods, however it picks right hint for student. The obvious workaround would be to just copy the docstring, but I'm going to have tens of different BaseChoice descendants, so it's just not practical.

I'm using PyCharm 3.1.1, both Community and Professional versions are affected.

Is it something completely missing in python itself, or just in PyCharm?

1
I'm also using PyCharm 3.1.1 and I get suggestions for Bar's methods inside make_foo_from_bar. Does the same problem occur if you start from a fresh project? - Wander Nauta
Never mind, it seems your example is off - PyCharm deduces that bar is of type Bar even without any hints. - Wander Nauta
Looks like I've oversimplified it, I'll update the question in a minute. - J0HN

1 Answers

3
votes

PyCharm does not look at the superclass type hints when overriding methods. I don't know if this is a bug or a feature, although I would be leaning toward the latter: Python does not require overriding methods to have the same signatures or accept the same types as the methods they override. Put differently, type hints on BaseChoice are not automatically valid for RationalChoice.

What PyCharm does do, and what seems to be confusing you, is take a quick guess and decide that Student would be a sensible class for a parameter called student. There is no class Options, so that heuristic fails.

So if you really, really want type hints, there's really no alternative to specifying them everywhere you want them.

If you are using Python 3, you could try the new in-language type hint (annotation) syntax:

class RationalChoice(BaseChoice):
    def make_choice(self, student: Student, options: list):
        return