25
votes

I have two classes that look like this:

class BaseClass(object):

    def the_dct(self):
        return self.THE_DCT


class Kid(BaseClass):

    THE_DCT = {'vars': 'values'}


# Code i ll be running
inst = Kid()
print(inst.the_dct)

Inheritance has to be this way; second class containing THE_DCT and first class containing def the_dct.

It works just fine, but my problem is that i get a warning in Pycharm (unresolved attribute reference), about THE_DCT in BaseClass.

  • Is there a reason why it's warning me (as in why i should avoid it)?
  • Is there something i should do differently?
1
"Is there a reason why it's warning me?" - because in the BaseClass there is no THE_DCT. "Is there something i should do differently?" - you could include an empty dictionary THE_DCT = {} in BaseClass, or just ignore the warning. - jonrsharpe
PyCharm often warns things that will work, there are limits to how good code inspection can be (often due to budget and time...). - NDevox
@Scironic this specific implementation will work, but PyCharm is warning because e.g. BaseClass().the_dct() will fail. - jonrsharpe
@user5061 as long as it works properly (and is readable), there is no real danger. - NDevox
@user5061 so long as you clearly document that BaseClass shouldn't be instantiated directly, this won't be a problem. You could also look into abstract base classes. - jonrsharpe

1 Answers

22
votes

Within BaseClass you reference self.THE_DCT, yet when PyCharm looks at this class, it sees that THE_DCT doesn't exist.

Assuming you are treating this as an Abstract Class, PyCharm doesn't know that that is your intention. All it sees is a class accessing an attribute, which doesn't exist, and therefore it displays the warning.

Although your code will run perfectly fine (as long as you never instantiate BaseClass), you should really change it to:

class BaseClass(object):
    THE_DCT = {}

    def the_dct(self):
        return self.THE_DCT