Benefits of Using @staticmethod in Python

python

I was wondering if you use @staticmethod decorator in your code.

Personally I don't use it, since it takes more letters to write @staticmethod then self.

The only benefit (which comes to me) from using it may be a better clarity of a code, but since I usually write a method description for sphinx, I always state whether a method is using object or not.

Or maybe I should start using @staticmethod decorator ?

Best Answer

Whether to use @staticmethod or not depends on what you want to achieve. Ignoring the decorator because there is more to type is a rather silly reason (no offense!) and indicates that you have not understood the concept of a static method in Python!

Static methods are independent of the class and any class instance. They only use the class scope as a namespace. If you omit the @staticmethod decorator, you are creating an instance method that cannot be used without constructing an instance.

Here is a very simple class Foo:

>>> class Foo(object):
...    @staticmethod
...    def foo():
...       print 'foo'
...
...    def bar(self):
...       print 'bar'

Now, Foo.foo() is a static method that can be called directly:

>>> Foo.foo()
foo

Foo.bar() on the other hand is an instance method, that can only be called from instances (objects) of Foo:

>>> Foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)
>>> foo = Foo()
>>> foo.bar()
bar

To answer your question: If you want to define a static method, use @staticmethod. Otherwise, don't.

If you have a method that does not use self, and therefore could be written as a static method, ask yourself: Will you ever want to access this function from outside without having an instance? Most of the times, the answer will be: No.