Metaclasses help :-)

Michael Hudson mwh at
Thu Oct 31 15:20:28 CET 2002

sismex01 at writes:

> OK, so it seems I'm looking for my brain to explode,
> so be it :-)


> I'm looking to create a metaclass which will check __init__'s
> keyword arguments *before* they're passed to __init__.

I don't know what the best way to do this is.  This works:

def _oinit(self, **kw):
    print kw # your code goes here!
    if self.__oinit__:

def ArgChecker(name, bases, ns):
    ns["__oinit__"] = ns.get("__init__")
    ns["__init__"] = _oinit
    return type(name, bases, ns)

class Test:
    __metaclass__ = ArgChecker
    def __init__(self, a):
        print a

>>> Test(a=1)
{'a': 1}
<__main__.Test object at 0x13d670>

or there's this approach:

class ArgChecker2(type):
    def __call__(self, **kw):
        print kw
        return super(ArgChecker2, self).__call__(**kw)

class Test2:
    __metaclass__ = ArgChecker2
    def __init__(self, a):
        print a

>>> Test2(a=1)
{'a': 1}
<__main__.Test2 object at 0x13d6b0>

Hmm, perhaps my AutoReloader would be better off using that approach.

> Any tiny example will be very much appreciated.



  I wouldn't trust the Anglo-Saxons for much anything else.  Given
  they way English is spelled, who could trust them on _anything_ that
  had to do with writing things down, anyway?
                                        -- Erik Naggum, comp.lang.lisp

More information about the Python-list mailing list