Skip to content

Instantly share code, notes, and snippets.

@Tattoo
Created September 9, 2014 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tattoo/1af311023e786abdf8b4 to your computer and use it in GitHub Desktop.
Save Tattoo/1af311023e786abdf8b4 to your computer and use it in GitHub Desktop.
class ArgumentConversionException(Exception):
pass
def _validate(args, conversions):
args_len, conversions_len = len(args), len(conversions)
msg = None
if args_len < conversions_len:
msg = ('Too many conversion functions given: %d arguments given when '
'%d conversions got.' % (args_len, conversions_len))
if args_len > conversions_len:
msg = ('Not enough conversion function given: %d arguments given when '
'%d conversion got.' % (args_len, conversions_len))
for conv in conversions:
if conv == None:
continue
if not hasattr(conv, '__call__'):
msg = ('Given conversion function "%s" is not a callable. Is it a '
'function?' % str(conv))
break
if msg:
raise ArgumentConversionException(msg)
def convert_arguments(*conversions):
def outer(func):
def inner(self, *args, **kwargs):
_validate(args, conversions)
converted_args = []
for arg, conv in zip(args, conversions):
if not conv:
converted_args.append(arg)
continue
converted_args.append(conv(arg))
return func(self, *converted_args, **kwargs)
return inner
return outer
if __name__ == '__main__':
class test(object):
@convert_arguments(int, int)
def test_basic_case(self, a, b):
return a,b
@convert_arguments(int, None, int)
def test_skipping_arguments(self, a, b, c):
return a, b, c
@convert_arguments(int)
def test_too_few_conversions(self, a, b):
return a, b
@convert_arguments(int, None)
def test_too_many_conversions(self, a):
return a
@convert_arguments(int, object())
def test_invalid_conversion_functions(self, a, b):
return a,b
t = test()
a1, a2 = t.test_basic_case('1', '2')
assert isinstance(a1, int) and isinstance(a2, int)
a1, a2, a3 = t.test_skipping_arguments('1', 'asd', '2')
assert (isinstance(a1, int) and isinstance(a2, basestring) and
isinstance(a3, int))
try:
a1, a2 = t.test_too_few_conversions('1', '2')
raise AssertionError('Should have failed.')
except ArgumentConversionException:
pass
try:
a1 = t.test_too_many_conversions('1')
raise AssertionError('Should have failed.')
except ArgumentConversionException:
pass
try:
a1, a2 = t.test_invalid_conversion_functions('1', '2')
raise AssertionError('Should have failed.')
except ArgumentConversionException:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment