How to initialize classes (not instances) in Python?

deamon picture deamon · May 31, 2011 · Viewed 7.5k times · Source

I want to merge constraints from the current and inherited classes only once a class is loaded (not per object!).

class Domain(Validatable):

    constraints = {...}

To do this I defined a method _initialize_class_not_instance that should be called once for each class:

class Validatable:

    @classmethod
    def _initialize_class_not_instance(cls):
        # merge constraints from derived class and base classes
        pass

    __class__._initialize_class_not_instance() # doesn't work
    # Validatable._merge_constraints() # doesn't work too

The problem is that __class__ doesn't exist in this context and Validatable is not defined too. But I want to avoid, that the user of my API has to call the initialize method explicitely or has to use an additional class decorator.

Any ideas how to initialize the class?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · May 31, 2011

Use a metaclass.

class MetaClass(type):
  def __init__(cls, name, bases, d):
    type.__init__(cls, name, bases, d)
    cls.foo = 42

class MyClass(object):
  __metaclass__ = MetaClass

print MyClass.foo