Created
December 3, 2012 18:25
-
-
Save ksheedlo/4196897 to your computer and use it in GitHub Desktop.
Fun with Python decorators
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
HANDLERS = {} | |
def handler_decorator(*dargs, **dkwargs): | |
''' | |
This function is actually a decorator factory. | |
It makes decorators that take arguments. | |
''' | |
print "Ermuhgerd! Erm uh dehcruter!" | |
print dargs, dkwargs | |
def _handler(func): | |
''' | |
This is the decorator function. | |
It returns a wrapper function, and optionally does other things. | |
Let's have it register the wrapped function as a handler. | |
''' | |
def _wrapped(*args, **kwargs): | |
''' | |
This is the wrapper function. | |
The wrapper has the opportunity to do pre- and post-processing | |
on the wrapped function. It could be useful for unpacking request | |
arguments and serializing the result to JSON in a server api, for | |
instance. | |
''' | |
print "Ermuhgerd! Erm uh rerrper fehrchun!" | |
return func(*args, **kwargs) | |
HANDLERS[func.__name__] = _wrapped | |
return _wrapped | |
return _handler | |
@handler_decorator('foo', 'baz', word='Hi there!') | |
def foo(*args, **kwargs): | |
''' | |
Do something silly. | |
''' | |
print "ba" + ("z" * kwargs.get('count', 20)) | |
@handler_decorator('car', leet='Wheeeee!') | |
def bar(*args, **kwargs): | |
''' | |
Do something serious. | |
''' | |
print "q" + ("u" * kwargs.get('count', 20)) + "x" | |
if __name__ == "__main__": | |
foo_func = HANDLERS['foo'] | |
foo_func(count=10) | |
foo_func(count=30) | |
bar_func = HANDLERS['bar'] | |
bar_func(count=30) |
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
Ermuhgerd! Erm uh dehcruter! | |
('foo', 'baz') {'word': 'Hi there!'} | |
Ermuhgerd! Erm uh dehcruter! | |
('car',) {'leet': 'Wheeeee!'} | |
Ermuhgerd! Erm uh rerrper fehrchun! | |
bazzzzzzzzzz | |
Ermuhgerd! Erm uh rerrper fehrchun! | |
bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzz | |
Ermuhgerd! Erm uh rerrper fehrchun! | |
quuuuuuuuuuuuuuuuuuuuuuuuuuuuuux |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Today I used this pattern to refactor an API dispatch routine on a Django server I've been working on (Not on github, it's a private project :)). It's pretty slick!