Generic constructors and duplication of internal Python logic
Michele Simionato
michele.simionato at poste.it
Tue Apr 20 00:08:17 EDT 2004
jjl at pobox.com (John J. Lee) wrote in message news:<87k70bzlak.fsf at pobox.com>...
> michele.simionato at poste.it (Michele Simionato) writes:
> > Have you thought of performing the checks in the __call__ method
> > of a custom metaclass?
>
> No. How would that help?
I had in mind something like that:
class _WithConstructorChecked(type): # helper metaclass
def __call__(cls, *args, **kw):
assert len(args)<=2, "%s called with more than 2 args" % cls
assert kw.has_key("kw"), "%s needs a 'kw=' argument" % cls
return super(_WithConstructorChecked,cls).__call__(*args,**kw)
class WithConstructorChecked(object): # mixin class
__metaclass__ = _WithConstructorChecked
class C(WithConstructorChecked):
def __init__(self, *args, **kw):
pass
c=C(1,2,kw=3) # ok; try different signatures to get assertion errors
In this example the mixin class WithConstructorChecked ensures that C is
called with at least two positional arguments and a keyword argument named
'kw'. The code of class C is not touched at all, you just add
WithConstructorChecked to the list of its bases.
Is that what you are looking for?
Michele Simionato
More information about the Python-list
mailing list