Fix Python – `staticmethod` and `abc.abstractmethod`: Will it blend?

Question

Asked By – Ram Rachum

In my Python app I want to make a method that is both a staticmethod and an abc.abstractmethod. How do I do this?

I tried applying both decorators, but it doesn’t work. If I do this:

import abc

class C(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    @staticmethod    
    def my_function(): pass

I get an exception*, and if I do this:

class C(object):
    __metaclass__ = abc.ABCMeta

    @staticmethod    
    @abc.abstractmethod
    def my_function(): pass

The abstract method is not enforced.

How can I make an abstract static method?

*The exception:

File "c:\Python26\Lib\abc.py", line 29, in abstractmethod
 funcobj.__isabstractmethod__ = True
AttributeError: 'staticmethod' object has no attribute '__isabstractmethod__'

Now we will see solution for issue: `staticmethod` and `abc.abstractmethod`: Will it blend?


Answer

Starting with Python 3.3, it is possible to combine @staticmethod and @abstractmethod, so none of the other suggestions are necessary anymore:

@staticmethod
@abstractmethod
def my_abstract_staticmethod(...):

Further @abstractstatic is deprecated since version 3.3.

This question is answered By – gerrit

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0