Decorator Hand Out
Decorator Hand Out
Python Decorators
Arguments
Variable arguments and variable keyword arguments are necessary for
functions that accept arbitrary parameters.
*args and **kw
>>>
...
>>>
[2,
>>>
>>>
[3,
>>>
[4,
>>>
[5,
>>>
[6,
Syntactic Sugar
>>> @decorator
... def foo():
...
print "hello"
and:
>>> def foo():
...
print "hello"
>>> foo = decorator(foo)
and:
Parameterized decorators (need 2 closures)
>>> def limit(length):
...
def decorator(function):
...
@functools.wraps(function)
...
def wrapper(*args, **kw):
...
result = function(*args, **kw)
...
result = result[:length]
...
return result
...
return wrapper
...
return decorator
Closures
Closures are useful as function generators:
>>> def add_x(x):
...
def adder(y):
...
return x + y
...
return adder
>>>
>>>
>>>
15
>>>
17
Decorating classes
>>> class Cat(object):
...
def __init__(self, name):
...
self.name = name
...
...
@decorator
...
def talk(self, txt):
...
print '{0} said, "{1}"'.format(
...
self.name, txt)
...
...
@decorator2
...
def growl(self, txt):
...
print txt.upper()
>>> cat = Cat('Fred')
>>> cat.talk("Meow.")
before invocation
Fred said, "Meow."
after invocation
>>> cat.growl("GRRR.")
before func
GRRR.
after func
More Details
For an in depth explanation of the above check out my ebook, Guide to:
Learning Python Decorators. http://hairysun.com/books/decorators/
and:
>>> def echo(foo):
...
return foo
>>> echo = limit(5)(echo)
>>> echo('123456')
'12345'
add_5 = add_x(5)
add_7 = add_x(7)
add_5(10)
add_7(10)