How to do a Decorator Here?
Gregory Piñero
gregpinero at gmail.com
Tue Feb 20 16:09:33 EST 2007
On 2/20/07, Tim Mitchell <tmitchell at leapfrog3d.com> wrote:
> Hi Greg,
>
> Decorators would work fine if the the class you were working with was
> _yours_ (ie. you wrote it), the problem here is that string.Template is
> someone else's class that you're trying to modify.
>
> Here's how a decorator would work (unfortunately it involves subclassing)
>
> class myTemplate(string.Template):
> def decorator(func):
> def preprocess(*args, **kwargs):
> # do preprocessing here
> kwargs['var1'] = "greg"
> # call actual method
> return func(*args, **kwargs)
> return preprocess
>
> @decorator
> def substitute(self, *args, **kwargs):
> return string.Template.substitute(self, *args, **kwargs)
>
> alternatively, if you don't mind changing the string.Template class
> itself (and are sure that it's not used anywhere else that doesn't
> require preprocessing) try:
>
> _substitute = string.Template.substitute
> def subs(self, *args, **kwargs):
> # do preprocessing here
> kwargs['var1'] = "greg"
> return _substitute(self, *args, **kwargs)
> string.Template.substitute = subs
>
> Cheers
> Tim
>
Thanks Tim. that makes sense now. Turns out my approach was too
complicated anyway. I think I'm just going to use Cheetah :-)
But at least I know decorators a little better.
-Greg
More information about the Python-list
mailing list