74

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
bignum
  • 3,448
  • 3
  • 21
  • 18

1 Answers1

86

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.

Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
  • 23
    I think ``@staticmethod`` is the more appropriate here than ``@classmethod``, because it apparently doesn’t manipulate any class properties or state. – mcepl Oct 23 '15 at 21:02
  • Java programmers also use static methods – Christophe Roussy Jul 20 '16 at 09:24
  • 2
    Agreed .. As suggested by @mcepl , it should be `@staticmethod` – Harsha Biyani Apr 03 '19 at 11:02
  • Piling on to the other comments, for this use `staticmethod` if you still want the function to be part of the class. For more info, [see here](https://stackoverflow.com/a/1669524/1399491). – Alex W Jan 04 '22 at 19:07
  • I found this page useful: https://docs.quantifiedcode.com/python-anti-patterns/correctness/method_could_be_a_function.html – Foxy Fox Jun 02 '23 at 06:49