Idiomatic way of calling a static method

Viewed 53

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?
2 Answers

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).

I would argue that it is pythonic to call the staticmethod using

SomeClass.do_something(52)

From the source:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

Even if one were to call it on an instance, it would still only infer the class from it and execute the function

x = 123
x.__class__
<class 'int'>
Related