Savir
Savir

Reputation: 18418

Pylint: Method could be a function in base class

I was wondering what is the best way to handle a Pylint error complaining about a situation like in this example:

class Base:
    def some_funct(self) -> List:
        """
        Intended to be overwritten in child classes, but
        if not, it's ok to return an empty list
        """
        return []

class Child1(Base):
     def some_funct(self) -> List:
          # Now, this does actual stuff!!
          return [a for a in self.some_iterable]

class Child2(Base):
   # An empty list is fine for this one
   pass

Pylint is going to say that the Base.some_funct could be a function because it doesn't use self (which... is true, but I'd like self to stay there)

Is there a better solution that just marking it as pylint: disable? Which... I mean... if it's what it is, it is what it is and it's not a "deal breaker" , but if there's a better way, it'd be nice to know.

This is for Python 3.6, in case it's relevant.

Upvotes: 3

Views: 1131

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50126

Declare the method as a staticmethod to make pylint happy:

class Base:
    @staticmethod
    def some_funct() -> List:
        """
        Intended to be overwritten in child classes, but
        if not, it's ok to return an empty list
        """
        return []

Since the self parameter is passed implicitly under normal conditions, it is not part of a method's outward signature. This allows to define the method as a staticmethod in the base class and still replace it with a regular method in a derived class without changing the outward behaviour.

Upvotes: 2

Related Questions