creating classes with mix-ins

samwyse samwyse at
Mon May 11 14:16:14 EDT 2009

I'm writing a class that derives it's functionality from mix-ins.
Here's the code:

    def boilerplate(what):   # This used to be a decorator, but all of
        ##what = f.__name__  # function bodies turned out to be
        'Validate the user, then call the appropriate plug-in.'
        def template(self, which, username, password, *args):
            if not, password,
which, what):
                raise Exception('Unauthorised access')
            return getattr(, what)(which, *args)
        template.__name__ = what
        template.__doc__ = getattr(, what).__doc__
        return template

    class MetaWeblog(object):
        def __init__(self,
   = securityHandler()
   = blogHandler()
        newPost = boilerplate('newPost')
        editPost = boilerplate('editPost')
        getPost = boilerplate('getPost')
        # etc, etc, etc

I'd like to replace the method definitions with a loop:
        for what in attr_list:
            setattr(klass, what, boilerplate(what))

That begs the question of where I define 'klass' and 'attr_list'.
Should I use a class decorator, or a metaclass?  In favor of
decorators is that I can see how to do it; in favor of a metaclass is
that I get to learn how to use them.  ;-)  What are the other pros and
cons for each choice?

More information about the Python-list mailing list