Last active
April 11, 2017 22:13
-
-
Save louisswarren/b133a558e718f89e43375c7b5ddeb1cd to your computer and use it in GitHub Desktop.
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
# Type-checked functions in python (!) | |
# This is a terrible idea | |
embeddings = {} | |
def signature(*sigtypes): | |
def decorator(func): | |
def wrapped(*args): | |
types = sigtypes | |
if types[-1] == Ellipsis: | |
extra_types = (types[-2], ) * (len(args) - len(types) + 2) | |
types = types[:-2] + extra_types | |
if len(types) != len(args): | |
print(types) | |
raise TypeError("Wrong number of arguments") | |
newargs = [] | |
for arg, t in zip(args, types): | |
while not isinstance(arg, t): | |
if type(arg) not in embeddings: | |
raise TypeError("Type mismatch") | |
arg = embeddings[type(arg)](arg) | |
newargs.append(arg) | |
return func(*newargs) | |
return wrapped | |
return decorator | |
embeddings[int] = float | |
embeddings[str] = int | |
@signature(int) | |
def square(x): | |
print(x ** 2) | |
print("3 squared is", square(3)) | |
try: | |
square(None) | |
except TypeError as e: | |
print("square(None) gave", e) | |
@signature(str, float, ...) | |
def printsum(message, *nums): | |
print(message, sum(nums)) | |
printsum("The sum is", 1, 2, 3.1, 4.4, '5') | |
printsum("The sum is") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment