Search code examples
pythonstatic-methodsimplementsabstract-methods

In Python, what are the pros and cons of implementing an abstract method using a static method?


In Python, what are the pros and cons of implementing an abstract method using a static method?

For example,

import numpy as np


class ExponentialFamily:

    @abstractmethod
    def log_normalizer(self, q):
        raise NotImplementedError


class Multinomial(ExponentialFamily):

    @staticmethod
    def log_normalizer(q):
        max_q = np.maximum(0.0, np.amax(q))
        q_minus_max_q = q - max_q
        return max_q + np.logaddexp(-max_q, np.logaddexp.reduce(q_minus_max_q))

class NegativeBinomial(ExponentialFamily):

    def __init__(self, r):
        super().__init__()
        self.r = r

    def log_normalizer(self, q):
        return -self.r * np.log1p(-mf.exp(q))

On the one hand, I know that pylint will complain less about self being unused. On the other hand, it seems weird to use staticmethod here.

In a situation of cooperative multiple inheritance, I could not use staticmethod because I would need at least the true type to call super, and the superclass might want the self object. However, this is not such a situation.


Solution

  • On a purist OOP point of view, overriding a normal method with a static one is just heretic. But because of the way Python processes methods, it is perfectly allowed by the language.

    I will try a list of pro/con:

    Pros:

    • makes explicit that log_normalizer in Multinomial is independant of the instance
    • saves a pylint warning

    Cons:

    • OOP heretic. Purists will shout after you
    • disturbing design for programmers used to non dynamic languages like C++ or Java
    • uncommon design, that IMHO requires comments explaining the rationale for future readers/mantainers
    • maybe a consequence of a questionnable design: how can a method be non static in a base class (abstract should not matter) and static in a subclass