Search code examples
pythonstatic-methods

Idiomatic way of calling a static method


What is the pythonic way to call a static method from within the class?

class SomeClass:
    @staticmethod
    def do_something(x: int) -> int:
        return 2*x + 17

    def foo(self) -> None:
        print(self.do_something(52))      # <--- this one?
        print(SomeClass.do_something(52)) # <--- or that one?

Solution

  • This depends entirely on your use case since in the context of subclassing, these two approaches do different things. Consider the following:

    class OtherClass(SomeClass):
        @staticmethod
        def do_something(x: int) -> int:
            return 42
    
    OtherClass().foo()
    

    This will print 42 and 121 since self.do_something(52) uses the method resolution order while SomeClass.do_something(52) always refers to the same method (unless the name SomeClass got bound to a different object).