Bitwise
Bitwise

Reputation: 7805

Appropriate way to group static functions in python

What is the appropriate way to group together static functions in Python?

Considerations:

  1. Functions in the same group do not need to share a state or any information.
  2. There are several groups each containing 3 functions, all sharing a common "interface".

It seems like the solution would be creating a class for each group. This has the advantage of easily providing an interface by subclassing an abstract class. Also this is less messy then creating separate modules for groups. However, it makes no sense to instantiate these classes - they should really be static classes.

Any ideas what is the best way of designing this? Should I add @staticmethod to each method in each class or is there a more elegant way of doing it (e.g. declaring the whole class static)?

EDIT: Since the question was tagged as "opinion-based", I will ask more concretely: Is there anyway to declare a whole class static?

Upvotes: 4

Views: 1031

Answers (1)

Lemming
Lemming

Reputation: 4205

Is there anyway to declare a whole class static?

You can use a metaclass to achieve this. That way you can intercept the class-creation and replace all methods by static methods.

from types import FunctionType


class StaticMetaClass(type):
    def __new__(cls, name, bases, dct):
        def transform(f):
            if type(f) == FunctionType:
                return staticmethod(f)
            return f

        newdct = dict((k, transform(v)) for k, v in dct.iteritems())

        return type.__new__(cls, name, bases, newdct)


class StaticBase(object):
    __metaclass__ = StaticMetaClass


class Static(StaticBase):
    def func1():
        print "func1"

    def func2(a, b):
        print "func2", a, b


Static.func1()
Static.func2(1, "World")

[...] is there a more elegant way of doing it [...] ?

I will leave the question, whether this is more elegant, to you. However, the usage of metaclasses is generally discouraged, if it is avoidable. They tend to make code bases much more complicated and confusing. Also, many programmers are not very familiar with them. So, your code will become harder to maintain.

Upvotes: 2

Related Questions