Revised PEP 318 - Function/Method Decorator Syntax

Steven Taschuk staschuk at telusplanet.net
Thu Jun 12 03:01:13 CEST 2003


Quoth Michele Simionato:
  [...]
> IMHO, there is only one reasonable way of defining a "decorator": it
> should be defined as a descriptor class, that takes a function and returns 
> a descriptor object. classmethods and staticmethods work this way and 
> "protected" should be the same. Now, if 'protected' is such a decorator, 
> it would only accepts *functions* as input, not classmethod objects.

Functions are descriptors too, though (since they have __get__ for
the unbound/bound method machinery).  What if we thought of these
things as descriptor decorators instead of function decorators?
Then transitivity is no problem.  (Of course, they'd expect that
the descriptor they wrap would have a __get__ which provides a
callable.)

    def pre(prefunc):
        class prewrapper(object):
            def __init__(self, descriptor):
                self.descriptor = descriptor
            def __get__(self, obj, type_=None):
                func = self.descriptor.__get__(obj, type_)    # <--
                def prewrapped(*args, **kwargs):
                    prefunc(*args, **kwargs)
                    return func(*args, **kwargs)
                prewrapped.__doc__ = func.__doc__
                return prewrapped
        return prewrapper

For the specific intended use, it wouldn't matter that other
callables (types, instances of classes with __call__ ...) are not
necessarily also descriptors.

(The implementation above does have the wart that the prefunc
doesn't see the self argument.)

-- 
Steven Taschuk                           staschuk at telusplanet.net
"I'm always serious, never more so than when I'm being flippant."
                            -- _Look to Windward_, Iain M. Banks





More information about the Python-list mailing list