creating classes with mix-ins

samwyse samwyse at gmail.com
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
the
        ##what = f.__name__  # function bodies turned out to be
'pass'.
        'Validate the user, then call the appropriate plug-in.'
        def template(self, which, username, password, *args):
            if not self.security.isAuthorised(username, password,
which, what):
                raise Exception('Unauthorised access')
            return getattr(self.blog, what)(which, *args)
        template.__name__ = what
        template.__doc__ = getattr(self.blog, what).__doc__
        return template

    class MetaWeblog(object):
        def __init__(self,
                     securityHandler=SimpleSecurityHandler,
                     blogHandler=SimpleBlogHandler):
            self.security = securityHandler()
            self.blog = 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