Skip to content

Instantly share code, notes, and snippets.

@Achifaifa
Created June 30, 2016 17:23
Show Gist options
  • Save Achifaifa/b439c28ebe50fde963511de45f5fdf9f to your computer and use it in GitHub Desktop.
Save Achifaifa/b439c28ebe50fde963511de45f5fdf9f to your computer and use it in GitHub Desktop.
decorator to automatically convert python function parameters
from functools import wraps
conv={"int":int, "str":str, "bool":bool}
def arguments_as(typechoice):
def decorator(f):
@wraps(f)
def func_wrapper(*args, **kwargs):
return f(*[conv[typechoice](i) for i in args], **kwargs)
return func_wrapper
return decorator
@arguments_as("int")
def test_int(a):
return a+1
@arguments_as("str")
def test_str(a):
return a+" is a string"
@arguments_as("bool")
def test_bool(a):
return a is True or a is False
print test_int("1")
print test_str(1)
print test_bool([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment