Created
March 15, 2014 20:33
-
-
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
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 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