Search code examples
pythonpylint

Pylint error with abstract member variable


I have the following code:

class A(object):
    def random_function(self):
        print self.name

    def abstract_function(self):
        raise NotImplementedError("This is an abstract class")

class B(A):
    def __init__(self):
        self.name = "Bob"
        super(B, self).__init__()

    def abstract_function(self):
        print "This is not an abstract class"

Pylint reports error:

ID:E1101 A.random_function: Instance of 'A' has no 'name' member

It's true, but I don't care because A is abstract. Is there a way to get rid of this warning without just suppressing it?

Thanks


Solution

  • It is best to define name in A. Consider somebody (or you in couple weeks) wants to inherit from A and implements abstract_function:

    class C(A):
        def abstract_function(self):
            print 'This is not an abstract class'
    

    Now the following will raise an error even though nothing in C seems to be wrong:

    c = C()
    c.random_function()
    

    If you are using self.name in A it should be defined there (and let's say it should default to something sensible saying it's not ready to use):

    class A(object):
        name = None
        def random_function(self):
            print self.name
    

    This will make your code cleaner/less error-prone and you will also get rid of the pylint error.