Last active
August 29, 2015 14:16
-
-
Save garykpdx/369619e928ab14b7a210 to your computer and use it in GitHub Desktop.
A decorator that enforces a particular type/subtype for each parameter of a function
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
class enforce(object): | |
def __init__(self,*argtypes): | |
# the types that need to be enforced for each position arg[i] | |
self.argtypes = argtypes | |
def __call__(self,f): | |
def wrapper(*args): | |
# bail if the definition isn't set up to handle this many arguments | |
if len(self.argtypes) < len(args): | |
raise Exception('too many parameters passed in') | |
for i in range(len(args)): | |
#test if arg[i] is not the class/subclass for this position | |
if not issubclass(args[i].__class__, self.argtypes[i]): | |
t_arg = self.argtypes[i].__name__ | |
raise Exception('arg %d type %s invalid, should be %s' % (i, args[i].__class__, t_arg)) | |
return f(*args) | |
return wrapper | |
#example function | |
@enforce(int) | |
def foo(n): | |
print('n = %d' % n) | |
#example useage | |
foo(5) | |
foo('Hi') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment