Created
December 3, 2012 22:09
-
-
Save nvanderw/4198578 to your computer and use it in GitHub Desktop.
Decorators for nice left-and-right composition
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
API_HANDLERS = {} | |
def register_handler(func, name=None): | |
if name is None: | |
name=func.__name__ | |
API_HANDLERS[name] = func | |
return func | |
def dispatch(name, request): | |
return API_HANDLERS[name](request) |
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
from functools import partial | |
from dispatch import dispatch | |
from handlers import make_wrapper | |
# A function which is like map, but returns a tuple of the arguments. | |
tuple_map = make_wrapper(map, return_wrapper=tuple) | |
def argument_doubler((args, kwargs)): | |
"""A function on the (args, kwargs) pair which doubles the args tuple.""" | |
return (tuple_map(lambda x: 2 * x, args), kwargs) | |
@partial(make_wrapper, arg_wrapper=argument_doubler) | |
def double_and_add(x,y): | |
return x + y | |
print(double_and_add(1,2)) # Print 6 | |
print(dispatch('example_handler', "My request.")) |
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
from dispatch import register_handler | |
def identity(x): return x | |
def make_wrapper(func, arg_wrapper=identity, return_wrapper=identity): | |
""" | |
From a given function, create a new function which optionally wraps | |
the arguments and return value of the first. | |
Arguments: | |
func: The function (*args, **kwargs) -> A to transform. | |
arg_wrapper: A function (args, kwargs) -> (args, kwargs) which | |
transforms the arguments and keyword arguments before | |
passing them to func. | |
return_wrapper: Function A -> B to apply to the output of the function. | |
Returns: | |
A function (*args, **kwargs) -> B which composes func with | |
return_wrapper on the left and arg_wrapper on the right. | |
""" | |
def inner(*args, **kwargs): | |
"""The actual wrapped function""" | |
(args, kwargs) = arg_wrapper((args, kwargs)) | |
return return_wrapper(func(*args, **kwargs)) | |
return inner | |
@register_handler | |
def example_handler(request): | |
response = "Hello, world! The request is: '%s'" % (request,) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment