Generic constructors and duplication of internal Python logic

John J. Lee jjl at pobox.com
Thu Apr 22 17:40:47 EDT 2004


michele.simionato at poste.it (Michele Simionato) writes:

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

No. :-)

See my replies to Peter: I'm trying to re-use Python's own knowledge
of to get attributes assigned, without repetition (see my original
post for the kind of repetition that motivated me), and without simply
liberally assigning as attributes any old arguments that get passed
in.  Seems like it's not possible, though.  I don't see how a
metaclass helps here.


John



More information about the Python-list mailing list