3 ms·
Really, the only thing you need to wrap your head around to understand decorators is the concept of first-class functions (functions that can take functions as
by kaens 18y ago
Really, the only thing you need to wrap your head around to understand decorators is the concept of first-class functions (functions that can take functions as parameters and return functions).
If you understand those, and how they can be useful, the only remaining step to python's decorators is a syntactic transformation.
def decorate(func):
def wrapper(*args, **kwargs):
print "I'm decorated!"
return func(*args, **kwargs)
return wrapper
@decorate
def foo():
print "I'm foo!"
Above, @decorate is equivalent to having foo = decorate(foo) underneath the definition of foo. Decorate takes a function X as a parameter, creates a function Y that takes whatever arguments, prints a statement, and returns the value of calling Y with whatever arguments. It then returns the object representing X.
If you need a bunch of good examples of how first-class functions can be extremely useful, go through a bit of SICP ( http://mitpress.mit.edu/sicp/full-text/book/book.html http://mitpress.mit.edu/sicp/full-text/book/book.html ). It's a challenging tome, but well worth the effort.