Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm visual warning about unresolved attribute reference

Tags:

python

pycharm

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.

  • Is there a reason why it's warning me (as in why i should avoid it)?
  • Is there something i should do differently?
like image 962
user Avatar asked Jan 27 '15 13:01

user


People also ask

What does unresolved attribute reference mean in Python?

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.


2 Answers

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 
like image 70
dursk Avatar answered Sep 23 '22 20:09

dursk


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.

like image 32
Andrew Avatar answered Sep 23 '22 20:09

Andrew