Using 'apply' as a decorator, to define constants

Jonathan Fine jfine at
Fri Aug 21 15:36:35 CEST 2009


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


More information about the Python-list mailing list