Last active
August 29, 2015 14:04
-
-
Save d-plaindoux/d0e911c17277a4e412df to your computer and use it in GitHub Desktop.
Simple type specification in Python
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
# | |
# Simpla and Naive type checker ... | |
# | |
import inspect | |
class TypeCheckError(Exception): | |
pass | |
def verifyType(value, aType): | |
# Whole type checking rule must be done here. Simple one is done here | |
if inspect.isclass(aType) and isinstance(value,aType): | |
return value | |
if type(value) == aType: | |
return value | |
else: | |
raise TypeCheckError("%s is not a %s" % (value, aType)) | |
def verifyTypes(i, values, types): | |
if len(values) == i: | |
pass | |
else: | |
verifyType(values[i], types[i]) | |
verifyTypes(i + 1, values, types) | |
def verifyCoherence(values, types): | |
if len(values) != len(types): | |
raise TypeCheckError("takes exactly %s arguments (%s given)" % | |
(len(types), len(values))) | |
def sig(typeIn, typeOut): | |
def validate(f): | |
def __apply(*args, **kwargs): | |
verifyCoherence(args, typeIn) | |
verifyTypes(0, args, typeIn) | |
return verifyType(f(*args, **kwargs), typeOut) | |
return __apply | |
return validate | |
# | |
# Example ... | |
# Must be improved for class type and subtyping :-) | |
# | |
class A: | |
def __init__(self): | |
pass | |
def m(self): | |
return 42 | |
class C(A): | |
pass | |
@sig([A], int) | |
def tt(a): | |
return a.m() | |
@sig([int, int], int) | |
def add(a, b): | |
return a + b | |
if __name__ == '__main__': | |
print add(1, 3) | |
print tt(12) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment