Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the pylint message: Warning: Method could be a function

Tags:

python

oop

pylint

I have a python class and ran pylint against it. One message it gave was:

Warning: Method could be a function 

Is this telling me that it would be better to move this method out of the class because it doesn't use any instance variables?

In C# I would make this a static method. What's the most pythonic thing to do here?

like image 758
bignum Avatar asked Apr 20 '10 09:04

bignum


People also ask

What is the difference between Staticmethod and Classmethod in Python?

The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class.

What does @staticmethod do in Python?

The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.

How do you call a static method in Python?

If anything not using the decorator gives you a method that is more "static" because you can't even call it from an instance object. When you use @staticmethod you can call the method from both the class and class instance objects.


1 Answers

Moving it to a function is common, if it doesn't touch the class at all.

If it manipulates class attributes, use the classmethod decorator:

@classmethod def spam(cls, ...):    # cls is the class, you can use it to get class attributes 

classmethod and staticmethod (which is the same as the former, except that the method doesn't get a reference to the class from its first parameter) have been introduced quite recently. It means that some Python programmers are used to avoid static and class methods.

Some hardcore Python programmers will tell you that these decorators just complicate things; some other people (usually former C# or Java programmers) will tell you that using a function isn't object-oriented enough. I think it's just a matter of preference.

like image 118
Bastien Léonard Avatar answered Sep 28 '22 20:09

Bastien Léonard