Metaclasses help :-)

Michael Hudson mwh at python.net
Thu Oct 31 09:20:28 EST 2002


sismex01 at hebmex.com writes:

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

Welcome.

> 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__:
        self.__oinit__(**kw)

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}
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}
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.

HTH!

Cheers,
M.

-- 
  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