python – Why does pycharm propose to change method to static

python – Why does pycharm propose to change method to static

PyCharm thinks that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesnt use self.

If youre sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

Workaround #1

def bar(self):

def is_not_used(self):

Workaround #2 [Thanks @DavidPärsson]

# noinspection PyMethodMayBeStatic
def bar(self):

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didnt happen to do anything with the instance. If I made those static Id get TypeError: staticmethod object is not callable.

In support of the OPs consternation, suggesting you add staticmethod whenever you can, goes against the principle that its easier to make code less restrictive later, than to make it more — making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

Guesses as to why this warning exists:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorralls points out, it gets your attention when self was inadvertently left out of the function.
  • Its a cue to rethink the object model; maybe the function does not belong in this class at all.

python – Why does pycharm propose to change method to static

I think that the reason for this warning is config in Pycharm.
You can uncheck the selection Method may be static in Editor->Inspection

Leave a Reply

Your email address will not be published. Required fields are marked *