Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. def annotated_func(args):
  2. def func_wrapper(func):
  3. def wrapper(*func_args):
  4. if len(args) == len(func_args):
  5. raise TypeError
  6. for i in args:
  7. if !isinstance(i, (type, TypedAny, TypedUnion,
  8. TypedList, TypedTuple, TypedDict,
  9. TypedSet, TypedCallable, TypedAnnotatedCallable)):
  10. raise TypeError
  11. func.__types__ = args
  12. return wrapper
  13. return func_wrapper
  14.  
  15.  
  16. class TypedAny:
  17. def __instancecheck__(self, instance):
  18. return True
  19.  
  20.  
  21. class TypedUnion:
  22. def __init__(self, types):
  23. self.types = types
  24.  
  25. def __instancecheck__(self, instance):
  26. return isinstance(instance, tuple(self.types))
  27.  
  28.  
  29. class TypedList:
  30. def __init__(self, T):
  31. self.T = T
  32.  
  33. def __instancecheck__(self, instance):
  34. if isinstance(instance, list):
  35. for i in instance:
  36. if not isinstance(i, self.T):
  37. return False
  38. return True
  39. else:
  40. return False
  41.  
  42.  
  43. class TypedTuple:
  44. def __init__(self, T):
  45. self.T = T
  46.  
  47. def __instancecheck__(self, instance):
  48. if isinstance(instance, tuple):
  49. for i in instance:
  50. if not isinstance(i, self.T):
  51. return False
  52. return True
  53. else:
  54. return False
  55.  
  56.  
  57. class TypedDict:
  58. def __init__(self, K, V):
  59. self.K = K
  60. self.V = V
  61.  
  62. def __instancecheck__(self, instance):
  63. if isinstance(instance, dict):
  64. for key, value in instance.items():
  65. if not isinstance(key, self.K) or not isinstance(value, self.V):
  66. return False
  67. return True
  68. else:
  69. return False
  70.  
  71.  
  72. class TypedSet:
  73. def __init__(self, T):
  74. self.T = T
  75.  
  76. def __instancecheck__(self, instance):
  77. if isinstance(instance, set):
  78. for i in instance:
  79. if not isinstance(i, self.T):
  80. return False
  81. return True
  82. else:
  83. return False
  84.  
  85.  
  86. class TypedCallable:
  87. def __instancecheck__(self, instance):
  88. return callable(instance)
  89.  
  90.  
  91. class TypedAnnotatedCallable:
  92. def __init__(self, types):
  93. self.types = types
  94.  
  95. def __instancecheck__(self, instance):
  96. if callable(instance):
  97. types = iter(self.types)
  98. for i in instance.__types__:
  99. if not isinstance(i, next(types)):
  100. return False
  101. return True
  102. else:
  103. return False
  104.  
  105.  
  106. def type_check(func):
  107. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement