[Tutor] Function decorators

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 30 12:16:54 EST 2020


On 30/11/2020 14:39, Manprit Singh wrote:
> I tried to understand the concept of function decorators from various
> sources but couldn't .

They are a fairly advanced concept that is rarely
used (as in creating decorators) in every day programming.
Decorators are easy enough to use once created even if you
don't understand what they do under the covers.
But creating a decorator is slightly more complex.

In essence a decorator is a function that returns
a function and then gets called through a bit of
Python syntactical magic - the @prefix.

Before understanding decorators do you understand
the concept of functions as objects? Are you
comfortable with lambdas? Lambdas aren't needed
for decorators but if you understand what lambdas
do you will find it a shorter step to decorators.

For example can you, without considering decorators,
define a function that returns a new function that
will calculate a given power?

def exponent_builder(n)
    def f(....
    return f

square = exponent_builder(2)
print(square(7) )   -> prints 49

triple = exponent_builder(3)
print( triple(3))  -> prints 27

If you can write exponent_builder() you are well
on the way to writing a decorator.

> I am sorry if I said something wrong.

No, it's a reasonable question. You will need to
be more specific now in any follow-up.


-- 
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