Search notes:

Python: __build_class__

The built-in function __build_class__ is called when a class is built with the class statement.
This function can be reassigned to another function which allows to hook into the creation process of classes:
build_class_orig = __build_class__

def build_class_hook(func, className, *baseClasses, **kw):

    print('Class', className, 'is being created')
    print('  This class derives from the following base classes: {}'.format( ', '.join([cls.__name__ for cls in baseClasses]) ))

    return build_class_orig(func, className, *baseClasses, **kw)

import builtins
builtins.__build_class__ = build_class_hook

class BASE:

      def __init__(self, ident):
          self.ident = ident

      def printIdent(self):
          print(self.ident)


class DERIV(BASE):

      def __init__(self, ident):
          BASE.__init__(self, ident)


base  = BASE(1)
deriv = DERIV(2)

base.printIdent()
deriv.printIdent()
Github repository about-python, path: /builtin-functions/__build_class__/hook.py

Index