Interesting decorator use.

Steven Bethard steven.bethard at gmail.com
Thu Feb 24 17:07:26 EST 2005


I wrote:
> Tom Willis wrote:
> 
>> Question on decorators in general. Can you parameterize those?
>
[snip]
> 
> If you want to call prepostdecorator with 2 arguments, you need to write 
> it this way.  A few options:

Sorry, I forgot my favorite one:

(4) Use a class and functional.partial:

py> class prepostdecorator(object):
...     def __init__(self, pre, post, function):
...         self.pre, self.post, self.function = pre, post, function
...     def __call__(self, *args, **kwargs):
...         self.pre()
...         result = self.function(*args,**kwargs)
...         self.post()
...         return result
...
py> @partial(prepostdecorator, dopre, dopost)
... def sayhello(name):
...     print "Hey %s, nice to meet you" % name
...
py> sayhello('Tom')
call pre
Hey Tom, nice to meet you
call post

Woo-hoo, I got rid of all the nested functions!  ;)

STeVe



More information about the Python-list mailing list