Skip to content

Instantly share code, notes, and snippets.

@ksheedlo
Created December 3, 2012 18:25
Show Gist options
  • Save ksheedlo/4196897 to your computer and use it in GitHub Desktop.
Save ksheedlo/4196897 to your computer and use it in GitHub Desktop.
Fun with Python decorators
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)
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
@ksheedlo
Copy link
Author

ksheedlo commented Dec 4, 2012

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment