Skip to content

Instantly share code, notes, and snippets.

@chipbell4
Created March 15, 2014 20:33
Show Gist options
  • Save chipbell4/9573549 to your computer and use it in GitHub Desktop.
Save chipbell4/9573549 to your computer and use it in GitHub Desktop.
A Python Decorator for type-checking function args, similar in vein to PHP type-hinting
class typecheck:
def __init__(self, *args):
self.types = args
def __call__(self, F):
# create a new function that checks
# the function types first
def typechecked_F(*args):
for expected_type, arg in zip(self.types, args):
if not isinstance(arg, expected_type):
raise Exception('NOT CORRECT TYPE')
return F(*args)
return typechecked_F
@typecheck(int, int)
def add(X, Y):
return X + Y
print( add(1,2) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment