Using 'apply' as a decorator, to define constants

Jonathan Fine jfine at pytex.org
Fri Aug 21 09:36:35 EDT 2009


Hi

It might seem odd to use 'apply' as a decorator, but it can make sense.

I want to write:
     # Top level in module.
     tags =  <complicated list>
where the list is most easily constructed using a function.

And so I write:
     @apply
     def tags():
         value = []
         # complicated code
         return value

And now 'tags' has the result of running the complicated code.


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


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 way to read
     @apply
     def name():
          # code
is that we are defining 'name' to be the return value of the effectively 
anonymous function that follows.

-- 
Jonathan



More information about the Python-list mailing list