Using 'apply' as a decorator, to define constants

Jonathan Gardner jgardner at jonathangardner.net
Fri Aug 21 18:17:40 EDT 2009


On Aug 21, 9:09 am, alex23 <wuwe... at gmail.com> wrote:
> On Aug 21, 11:36 pm, Jonathan Fine <jf... at pytex.org> wrote:
>
> 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())
>

This is brilliant. I am going to use this more often. I've all but
given up on property() since defining "get_foo", "get_bar", etc... has
been a pain and polluted the namespace.


> 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.

    apply = lambda f: f()

It's one of those functions that is easier to define than import.


> 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.
>

If anyone reads the decorator and doesn't think "this thing below is
defined as the result of this decorator function" then they don't
understand decorators at all.



More information about the Python-list mailing list