Created
July 22, 2015 09:25
-
-
Save pmuller/6c68b1d365cb80c350ce to your computer and use it in GitHub Desktop.
decorators examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add(x, y): | |
return x + y | |
def dummy_decorator(func): | |
"""This decorator does NOT modify ``func`` behavior. | |
It only prints stuff. | |
""" | |
print 'creating wrapper' | |
def wrapper(*args, **kwargs): | |
print 'before' | |
result = func(*args, **kwargs) | |
print 'after' | |
return result | |
print 'wrapper created' | |
return wrapper | |
def inc_decorator(func): | |
"""This decorator increments ``func``'s result by one. | |
""" | |
def wrapper(*args, **kwargs): | |
return func(*args, **kwargs) + 1 | |
return wrapper | |
class IncDecorator(object): | |
def __init__(self, func, increment=1): | |
self.func = func | |
self.increment = increment | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) + self.increment | |
add_dummy = dummy_decorator(add) | |
add_plus_one_func = inc_decorator(add) | |
add_plus_one_class = IncDecorator(add) | |
assert add(1, 1) == 2 | |
assert add_dummy(1, 1) == 2 | |
assert add_plus_one_func(40, 1) == 42 | |
assert add_plus_one_class(40, 1) == 42 | |
# Of course, all these decorators can be used via the decorator notation: | |
# | |
# @inc_decorator | |
# def add(x, y): | |
# return x + y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment