Design: Idiom for classes and methods that are customizable by the user?

Michael Selik michael.selik at gmail.com
Fri May 13 16:33:11 EDT 2016


On Fri, May 13, 2016 at 2:41 AM Gregory Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Dirk Bächle wrote:
> > I'm currently following the "Factory" pattern (more or less) as I know
> > it from C++ and similar languages.
>
> This statement sets off alarm bells for me. If you're using some
> design pattern in Python just because you learned to do it that
> way in C++/Java/whatever, you're probably making it more
> complicated than it needs to be.
>

I share Greg's trepidation when I hear a phrase like that, but the general
idea of a registry of classes or functions and then picking the right one
based on string input is fine.

How would the API work for custom Taskmasters? It's not so great to require
that the user must explicitly ``add`` their derived class after defining
it. Perhaps that add function could be a decorator?

def register(key):
    def decorator(cls):
        if not issubclass(cls, Taskmaster):
            raise TypeError('You fool!')
        registry[key] = cls
    return decorator

@register('noclean')
class NoCleanTaskMaster(TaskMaster):
    "Looks clean enough, why worry?"



More information about the Python-list mailing list