Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def annotated_func(args):
- def func_wrapper(func):
- def wrapper(*func_args):
- if len(args) != len(func_args):
- raise TypeError
- for i in args:
- if not isinstance(i, (type, TypedAny, TypedUnion,
- TypedList, TypedTuple, TypedDict,
- TypedSet, TypedCallable, TypedAnnotatedCallable)):
- raise TypeError
- func(*func_args)
- wrapper.__types__ = args
- return wrapper
- return func_wrapper
- class TypedAny:
- def __instancecheck__(self, instance):
- return True
- class TypedUnion:
- def __init__(self, types):
- self.x = types
- def __instancecheck__(self, instance):
- return isinstance(instance, tuple(self.x))
- class TypedList:
- def __init__(self, t):
- self.x = t
- def __instancecheck__(self, instance):
- if isinstance(instance, list):
- for i in instance:
- if not isinstance(i, self.x):
- return False
- return True
- else:
- return False
- class TypedTuple:
- def __init__(self, t):
- self.x = t
- def __instancecheck__(self, instance):
- if isinstance(instance, tuple):
- for i in instance:
- if not isinstance(i, self.x):
- return False
- return True
- else:
- return False
- class TypedDict:
- def __init__(self, k, v):
- self.k = k
- self.v = v
- self.x = tuple(k, v)
- def __instancecheck__(self, instance):
- if isinstance(instance, dict):
- for key, value in instance.items():
- if not isinstance(key, self.k) or not isinstance(value, self.v):
- return False
- return True
- else:
- return False
- class TypedSet:
- def __init__(self, t):
- self.x = t
- def __instancecheck__(self, instance):
- if isinstance(instance, set):
- for i in instance:
- if not isinstance(i, self.x):
- return False
- return True
- else:
- return False
- class TypedCallable:
- def __instancecheck__(self, instance):
- return callable(instance)
- class TypedAnnotatedCallable:
- def __init__(self, types):
- self.types = types
- self.x = types
- def __instancecheck__(self, instance):
- if callable(instance):
- if len(self.types) == len(instance.__types__):
- types = iter(self.types)
- for i in instance.__types__:
- it = next(types)
- if not check(i, it):
- return False
- return True
- else:
- return False
- else:
- return False
- def check(i, it):
- if isinstance(i, type) and (isinstance(it, type)):
- if not(i is it):
- return False
- else:
- return True
- elif (type(i) == type(it) or (issubclass(type(i), type(it)))
- or issubclass(type(it), type(i))):
- return True
- elif (type(i) != type(it) and not(issubclass(type(i), type(it)))
- and not(issubclass(type(it), type(i)))):
- return False
- else:
- return check(i.x, it.x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement