color version - PET: Python Entre Todos - Python Argentina
color version - PET: Python Entre Todos - Python Argentina
color version - PET: Python Entre Todos - Python Argentina
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
def sum(a, b):<br />
return a + b<br />
def my_function(some, arguments):<br />
# function's body<br />
sum = d(sum)<br />
Is equivalent to:<br />
@d<br />
def sum(a, b):<br />
return a + b<br />
In the above code snippet you can see two examples where we compare the different<br />
ways of applying a decorator.<br />
Next there are some examples of real decorators.<br />
Warning<br />
Counter-example: the evil decorator.<br />
def evil(f):<br />
return False<br />
>>> @evil<br />
... def something():<br />
... return 42<br />
...<br />
>>> something<br />
False<br />
>>> something()<br />
Traceback (most recent call last):<br />
File "", line 1, in <br />
TypeError: 'bool' object is not callable<br />
This is a cheater decorator, because instead of returning a new function, it returns a<br />
boolean object. Obviously when we try to run it, we get an error.<br />
Chained decorators<br />
Their application is similar to the mathematical concept of function composition.<br />
@register_use<br />
@measure_execution_time<br />
def my_function(some, arguments):<br />
# function's body<br />
my_function = register_use(measure_execution_time(my_function))<br />
Decorators with parameters<br />
• They allow more flexible decorators.<br />
• Example: a decorator that forces a return type of a function.<br />
Suppose we want a decorator that converts to string all a function’s returns. You could<br />
use this way:<br />
@to_string<br />
def count():<br />
return 42<br />
>>> count()<br />
'42'<br />
How would you implement that See a first approach:<br />
def to_string(f):<br />
def inner(*args, **kwargs):<br />
return str(f(*args, **kwargs))<br />
return inner<br />
This way works, but think if we can do this in a more generic way. Below you’ll find the<br />
use form of a decorator named typer:<br />
@typer(str)<br />
def c():<br />
return 42