Beruflich Dokumente
Kultur Dokumente
@cache
def factorize(n):
factors = []
# calculate factors of n
# takes lots of time for large n
return factors
separation of concerns
example: you can work the function and not the caching
Improved readability
Decorator Syntax
stackable
prefixed with ‘@’
can have arguments
same for functions, methods and classes
@assert_inputs
@log_event
@validate_item
def itemable(x, y, z):
a = x * y * z
return a
Typical uses
preconditions and post-conditions
Assert types
check returned values
authentication
authorization
debugging
logging
locking of resources (threading, io, database)
threads
hardware
Classic decorators
Properties! (A favorite of mine!)
class Love(object):
@property
def fiancée(self):
return 'Audrey Roy'
Let’s write a decorator!
See PEP 318
Because functions are objects you can pass them around with state and all that…
def trig_power(trig_func):
print "Storing function=", trig_func
if __name__ == "__main__":
sine_power = trig_power(math.sin)
tan_power = trig_power(math.tan)
Another example:
def report_entry(func):
print 'Just entered a %s function' % func
return func
@report_entry
def add2(n):
''' I add two '''
return n + 2
if __name__ == "__main__":
print add2(5)
help(add2)
def wrapper(*args):
''' our internal wrapper thingee '''
print 'This will be our docs issue'
return func(*args)
return wrapper
@report_entry
def add2(n):
''' I add two '''
return n + 2
if __name__ == "__main__":
print add2(5)
help(add2)
def report_entry(func):
print 'Just entered a %s function' % func
@wraps(func)
def wrapper(*args):
''' our internal wrapper thingee '''
print 'This will be our docs issues'
return func(*args)
return wrapper
@report_entry
def add2(n):
''' I add two '''
return n + 2
if __name__ == "__main__":
print add2(5)
help(add2)
Class decorators
Added in Python 2.6.+ and Python 3
Singletons
Class checks
Some advice
beware the spaghetti!
No hidden surprises