I have two classes that look like this:
class BaseClass: def the_dct(self): return self.THE_DCT class Kid(BaseClass): THE_DCT = {'key': 'value'} # 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
.
Answered. Jaap van der Velde. Created October 14, 2018 21:00. In a very basic bit of example code, PyCharm is generating a warning "Unresolved attribute reference" and of course this means code completion also does not work. The code is perfectly functional however and runs as expected.
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
In addition to the existing answers, or as an alternative, you can use Type Hints
. This satisfies PyCharm's warnings and also distinguishes the attribute as being inherited (or at least not native to the class). It's as simple as adding THE_DCT: dict
at the very top of your class (before anything else).
class BaseClass(object): THE_DCT: dict # Add a type-hint at the top of the class, before anything else def the_dct(self): return self.THE_DCT class Kid(BaseClass): THE_DCT = {'vars': 'values'}
I prefer this approach because it negates the need to unnecessarily add a placeholder attribute (self.THE_DCT = {}
) and, because it's visually different than declaring an attribute, it can also negate the need for adding a comment next to the placeholder attribute to explain that it's inherited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With