Using 'apply' as a decorator, to define constants

alex23 wuwei23 at gmail.com
Fri Aug 21 18:09:02 CEST 2009


On Aug 21, 11:36 pm, Jonathan Fine <jf... at pytex.org> wrote:
> It might seem odd to use 'apply' as a decorator, but it can make sense.

Yes, it's an idiom I've used myself for property declarations, but one
I find myself using less often:

class ColourThing(object):
    @apply
    def rgb():
        def fset(self, rgb):
            self.r, self.g, self.b = rgb
        def fget(self):
            return (self.r, self.g, self.b)
        return property(**locals())

Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
sure if it has been relocated to a module somewhere, there's no
mention of such in the docs.

> Without using 'apply' as a decorator one alternative is
>      def tmp():
>          value = []
>          # complicated code
>          return value
>      tags = tmp()
>      del tmp

You can save yourself the tidy up by using the same name for the
function & the label:

    def tags():
        value = []
        # ...
        return value
    tags = tags()

> Like all uses of decorators, it is simply syntactic sugar.  It allows
> you to see, up front, what is going to happen.  I think, once I get used
> to it, I'll get to like it.

The question is, is it really that useful, or is it just a slight
aesthetic variation? Given that apply(f, args, kwargs) is identical to
f(*args, **kwargs), it's understandable that's apply() isn't seen as
worth keeping in the language.

Why I've personally stopped using it: I've always had the impression
that decorators were intended to provide a convenient and obvious way
of augmenting functions. Having one that automatically executes the
function at definition just runs counter to the behaviour I expect
from a decorator. Especially when direct assignment... foo = foo
() ...is a far more direct and clear way of expressing exactly what is
happening.

But that's all IMO, if you feel it makes your code cleaner and don't
plan on moving to 3.x any time soon (come on in! the water's great!),
go for it :)



More information about the Python-list mailing list