[Tutor] Writing decorators?
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jul 5 10:40:30 EDT 2016
On 05/07/16 14:22, Alex Hall wrote:
> To simplify things, what might be an example of a decorator that, say,
> prints "decorated" before whatever string the decorated function prints?
> My attempt would be:
>
> def prependDecorated(f):
> def prepend():
> return "decorated"+f()
> #something should go at this level too?
Recall that a decorator is:
a function
that takes a function as its argument
and returns a function
Your code fails on the third item.
Lets take a trivial example first, a decorator that
does nothing. Define a function that takes a function
and returns the same function untouched:
>>> def donothing(f): return f
Now apply it to a square() function:
>>> @donothing
def square(x): return x*x
>>> square
<function square at 0x7f3633fcb0d0>
>>> square(4)
16
We could do the same without the @ shorthand by using
square2 = donothing(square)
But the @ syntax makes it more readable.
Now lets look at your task
We need a function that takes a function and
returns a function that prepends a string:
def prepend(f):
def add_string(*args, **kwargs): # in case f takes arguments
return "decorated "+ str(f(*args,**kwargs))
return add_string
Now we can apply that to a function
@prepend
def cube(n): return n*n*n
cube(3)
I'm biased because I was the tech editor but the book
Professional Python has a nice chapter on decorators.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list