function decorator-like function

vsoler vicente.soler at gmail.com
Sat Mar 27 12:21:06 EDT 2010


On 27 mar, 17:06, Patrick Maupin <pmau... at gmail.com> wrote:
> On Mar 27, 10:24 am, vsoler <vicente.so... at gmail.com> wrote:
>
>
>
> > Hi,
>
> > Still learning Python, now decorators.
>
> > Before diving deeply into decorators, I'd like to apply a function to
> > another function.
>
> > My "extremely simple function" should print number 3, then the sum of
> > its 2 arguments.
>
> > Say that I call   f(5,7)
> > I'd like to get, somehow, 3 then 12.
>
> > I've tried the following:
>
> > def d(f):
> >     print 3
> >     return f
>
> > def f(a, b):
> >     print a+b
>
> > f=d(f)
>
> > However, it does not work. Calling f(5,7) only returns 12, (3 is
> > missing)
> > How should I proceed?
> >>> def d(f):
>
> ...     def wrapper(*args):
> ...         print 3
> ...         return f(*args)
> ...     return wrapper
> ...>>> def f(a, b):
>
> ...     print a + b
> ...>>> f = d(f)
> >>> f(5, 7)
>
> 3
> 12
>
> HTH,
> Pat

Pat,

I think some lines are missing. I don't see "d" function defined. Any
lines above def wrapper?

Thank you



More information about the Python-list mailing list