How to do a Decorator Here?

Goldfish gregturn at mindspring.com
Tue Feb 20 15:38:00 EST 2007


On Feb 20, 8:20 pm, "Gregory Piñero" <gregpin... at gmail.com> wrote:
> Need some decorator help.
>
> I have a class.  And I want to add behavior to one of this class's
> methods to be run before the class runs the actual method.  Is this
> what decorators are for?
>
> So the class I want to work with is string.Template
>
> Let's say I have this:
> from string import Template
> a=Template("$var1 is a test")
>
> def preprocess(var1):
>    #Real code here will be more complicated, just an example
>     var1=var1.upper()
>
> a.substitute(var1="greg")
>
> So how can I have preprocess run before substitute is run?  I want the
> user to be able to call a.substitute and have preprocess run
> automatically.
>
> Or is this not what decorators do?  I'm trying to avoid subclassing if I can.
>
> Thanks in advance for the help.
>
> -Greg

That sounds like aspect oriented programming. Spring Python (http://
springpython.python-hosting.com) offers a way to wrap objects with
method interceptors. Method interceptors give you full control before
and after method calls.

Sometimes decorators can be used to do that as well, but they have
constraints in where they can be used. I found them too inflexible for
my needs, so I built an AOP solution.

Greg




More information about the Python-list mailing list