Why does pycharm propose to change method to static

前端 未结 9 1517
面向向阳花
面向向阳花 2020-12-22 18:41

The new pycharm release (3.1.3 community edition) proposes to convert the methods that don\'t work with the current object\'s state to static.

9条回答
  •  生来不讨喜
    2020-12-22 18:50

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

    If you're 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):
        self.is_not_used()
        doing_something_without_self()
    
    def is_not_used(self):
        pass
    

    Workaround #2 [Thanks @DavidPärsson]

    # noinspection PyMethodMayBeStatic
    def bar(self):
        doing_something_without_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 didn't happen to do anything with the instance. If I made those static I'd get "TypeError: 'staticmethod' object is not callable".

    In support of the OP's consternation, suggesting you add staticmethod whenever you can, goes against the principle that it's 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 @JohnWorrall's points out, it gets your attention when self was inadvertently left out of the function.
    • It's a cue to rethink the object model; maybe the function does not belong in this class at all.

提交回复
热议问题