-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrictPy.py
More file actions
185 lines (161 loc) · 7.52 KB
/
Copy pathstrictPy.py
File metadata and controls
185 lines (161 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from typing import Any, Callable, Dict, List, Tuple, Union, get_type_hints, get_origin, get_args, Optional
from functools import wraps
import collections.abc
class StrictTypeError(TypeError):
def __init__(self, message: str, method_name: str, param_name: str, received_type: type, value: Any, code: int, context: Optional[str] = None):
self.message = (
f"[Error Code {code}] {message}\n"
f"In method '{method_name}', parameter '{param_name}': "
f"Expected {type.__name__}, but got {type(value).__name__} "
f"with value '{value}'."
)
if context:
self.message += f"\nContext: {context}"
super().__init__(self.message)
class strictMeta(type):
type_coercion_enabled = False
range_validators = {}
condition_validators = {}
custom_validators = {}
def __new__(cls, name, bases, dct):
for attrName, attrValue in dct.items():
if callable(attrValue) and not isinstance(attrValue, (staticmethod, classmethod)):
dct[attrName] = cls._wrapMethod(attrValue)
return super().__new__(cls, name, bases, dct)
@staticmethod
def enableTypeCoercion(enable: bool = True):
strictMeta.type_coercion_enabled = enable
@staticmethod
def addRangeValidator(type_: type, min_value: Optional[int] = None, max_value: Optional[int] = None):
strictMeta.range_validators[type_] = (min_value, max_value)
@staticmethod
def addConditionValidator(type_: type, condition: Callable[[Any], bool]):
strictMeta.condition_validators[type_] = condition
@staticmethod
def addCustomValidator(type_: type, validator: Callable[[Any], bool]):
strictMeta.custom_validators[type_] = validator
@staticmethod
def _wrapMethod(method: Callable):
methodHints = get_type_hints(method)
@wraps(method)
def wrapper(*args, **kwargs):
argNames = method.__code__.co_varnames
for idx, (argName, argValue) in enumerate(zip(argNames, args)):
strictMeta._validateType(argName, argValue, methodHints, method.__name__)
for kwargName, kwargValue in kwargs.items():
strictMeta._validateType(kwargName, kwargValue, methodHints, method.__name__)
result = method(*args, **kwargs)
if "return" in methodHints:
strictMeta._validateType("return value", result, methodHints, method.__name__)
return result
return wrapper
@staticmethod
def _validateType(name: str, value: Any, hints: Dict, method_name: str, context: Optional[str] = None):
expectedType = hints.get(name)
if expectedType:
originType = get_origin(expectedType)
argsType = get_args(expectedType)
if strictMeta.type_coercion_enabled:
try:
value = expectedType(value)
except Exception:
pass
if isinstance(value, collections.abc.Mapping):
if originType is dict:
key_type, value_type = argsType
for key, val in value.items():
strictMeta._validateType(name, key, {name: key_type}, method_name, context)
strictMeta._validateType(name, val, {name: value_type}, method_name, context)
return
if isinstance(value, collections.abc.Sequence):
if originType in {list, tuple}:
if argsType:
for item in value:
strictMeta._validateType(name, item, {name: argsType[0]}, method_name, context)
return
if expectedType in strictMeta.range_validators:
min_value, max_value = strictMeta.range_validators[expectedType]
if isinstance(value, (int, float)):
if min_value is not None and value < min_value:
raise StrictTypeError(
f"'{name}' must be greater than or equal to {min_value}.",
method_name,
name,
expectedType,
value,
code=105,
context=context,
)
if max_value is not None and value > max_value:
raise StrictTypeError(
f"'{name}' must be less than or equal to {max_value}.",
method_name,
name,
expectedType,
value,
code=106,
context=context,
)
if expectedType in strictMeta.condition_validators:
condition = strictMeta.condition_validators[expectedType]
if not condition(value):
raise StrictTypeError(
f"'{name}' does not satisfy the condition.",
method_name,
name,
expectedType,
value,
code=107,
context=context,
)
if expectedType in strictMeta.custom_validators:
validator = strictMeta.custom_validators[expectedType]
if not validator(value):
raise StrictTypeError(
f"'{name}' failed custom validation.",
method_name,
name,
expectedType,
value,
code=109,
context=context,
)
if not isinstance(value, expectedType):
raise StrictTypeError(
f"'{name}' must be of type {expectedType.__name__}.",
method_name,
name,
expectedType,
value,
code=104,
context=context,
)
class strictClass(metaclass=strictMeta):
def __setattr__(self, name, value):
if hasattr(self, name):
raise StrictTypeError(
f"Cannot modify immutable attribute '{name}'",
self.__class__.__name__,
name,
type(value),
value,
code=108,
)
classHints = get_type_hints(self.__class__)
if name in classHints:
strictMeta._validateType(name, value, classHints, self.__class__.__name__)
super().__setattr__(name, value)
def strictFunction(func: Callable):
funcHints = get_type_hints(func)
@wraps(func)
def wrapper(*args, **kwargs):
argNames = func.__code__.co_varnames
for idx, (argName, argValue) in enumerate(zip(argNames, args)):
strictMeta._validateType(argName, argValue, funcHints, func.__name__)
for kwargName, kwargValue in kwargs.items():
strictMeta._validateType(kwargName, kwargValue, funcHints, func.__name__)
result = func(*args, **kwargs)
if "return" in funcHints:
strictMeta._validateType("return value", result, funcHints, func.__name__)
return result
return wrapper