Skip to content

Instantly share code, notes, and snippets.

@Aaron2Ti
Created January 4, 2017 12:01
Show Gist options
  • Save Aaron2Ti/8e83864daa780fcea3fe1a07d0b523f8 to your computer and use it in GitHub Desktop.
Save Aaron2Ti/8e83864daa780fcea3fe1a07d0b523f8 to your computer and use it in GitHub Desktop.
from functools import wraps
def juggle(f):
"""
Suppose we have a binary function
>>> def add(a, b):
... return a + b
You could call `it` in following way
>>> add(1, 2)
3
however if we `juggle` the function,
>>> juggled_add = juggle(add)
then the juggled function would take single tuple as `args`,
and apply *args to unwrapped function
>>> juggled_add((1, 2))
3
>>> juggled_add([1, 2])
Traceback (most recent call last):
...
TypeError: Function `juggle(add)` takes exactly 1 argument, which must be a tuple
>>> from itertools import product
>>> from operator import concat
>>> map(juggle(concat), product([[1], [2]], [[1]]))
[[1, 1], [2, 1]]
"""
@wraps(f)
def wrapper(*args, **kwargs):
if len(kwargs) == 0 and len(args) == 1 and isinstance(args[0], tuple):
return f(*args[0])
else:
raise TypeError('Function `juggle({})` takes exactly'
' 1 argument, which must be a tuple'.format(f.__name__))
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment