Skip to content

Instantly share code, notes, and snippets.

@garykpdx
Last active August 29, 2015 14:16
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 garykpdx/369619e928ab14b7a210 to your computer and use it in GitHub Desktop.
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
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