Like __getattr__ but with args and kwargs as well

Miki miki.tebeka at gmail.com
Fri May 28 13:39:51 EDT 2010


class MixedAuthorizer:
    def __init__(self, *args):
        # expected a list of class instances
        self.authorizers = args
        self._set_methods()

    def _set_methods(self):
        for attr in ("home", "password"):
            def fn(user):
                return self._get_attr(user, attr)
            setattr(self, "get_%s" % attr, fn)

    def _get_attr(self, user, attr):
        auths = [auth for auth in self.authorizers if
auth.has_user(user)]
        if not auths:
            return ""

        method_name = "get_%s" % attr
        method = getattr(auths[0], method_name, None)
        if not fn:
            raise ValueError("Unknown attribute - %s" % method_name)

        return fn(user)

HTH,
--
Miki
http://pythonwise.blogspot.com



More information about the Python-list mailing list