Created
May 4, 2013 17:07
-
-
Save russelldavis/5518097 to your computer and use it in GitHub Desktop.
For each set of args, makes a copy of the function with the args bound, and
with the repr of the args appended to the name. Assigns that to the calling
frame's locals. Adapted from http://stackoverflow.com/a/4455312/278488.
Meant for use with unit tests, to create multiple tests from a parameterized
method.
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 expand_with_args(*parameters, **kwargs): | |
""" | |
For each set of args, makes a copy of the function with the args bound, and | |
with the repr of the args appended to the name. Assigns that to the calling | |
frame's locals. Adapted from http://stackoverflow.com/a/4455312/278488. | |
Meant for use with unit tests, to create multiple tests from a parameterized | |
method. | |
""" | |
def tuplify(x): | |
if not isinstance(x, tuple): | |
return x, | |
return x | |
def _arg_namer(arg): | |
return repr(arg) | |
arg_namer = kwargs.pop('arg_namer', _arg_namer) | |
def _args_namer(*args): | |
return ",".join(arg_namer(arg) for arg in args) | |
args_namer = kwargs.pop('args_namer', _args_namer) | |
if kwargs: | |
raise TypeError('Unexpected keyword arguments %r' % kwargs) | |
def decorator(method, parameters=parameters): | |
for parameter in (tuplify(x) for x in parameters): | |
def wrapper(self, method=method, parameter=parameter): | |
method(self, *parameter) | |
name_for_parameter = args_namer(*parameter) | |
wrapper.__name__ = "%s(%s)" % (method.__name__, name_for_parameter) | |
frame = sys._getframe(1) # pylint: disable-msg=W0212 | |
frame.f_locals[wrapper.__name__] = wrapper | |
return None | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment