-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject_condition_checker.py
More file actions
425 lines (340 loc) · 16.6 KB
/
object_condition_checker.py
File metadata and controls
425 lines (340 loc) · 16.6 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""
Condition Evaluation Module
===========================
Description:
This module provides tools for creating, evaluating, and serializing conditional logic on object attributes.
It includes classes to define individual attribute conditions, combine them with logical operators,
and evaluate them against specified objects.
Contents:
Classes:
- ObjectCondition: Represents a condition for evaluating an object's attribute based on
a comparison operator and value. Supports various data types, including numbers, strings, dates,
and more.
- ConditionList: Represents a collection of ObjectCondition or ConditionList instances that are
evaluated together using a specified logical operator (AND/OR).
Functions:
- is_debug(): Utility function to toggle debugging output.
Usage:
Example usage:
condition = ObjectCondition("age", ">=", 18, "int")
another_condition = ObjectCondition("status", "==", "active", "str")
condition_list = ConditionList(condition, another_condition, operator="and")
obj = YourClass(age=20, status="active")
result = condition_list.is_true(obj)
This example checks if the object `obj` has an `age` of at least 18 and a `status` of "active".
Dependencies:
Requires Python standard library modules `datetime` and `json`
Author:
Sora_7672 - https://github.com/sora7672
License:
MIT License
"""
from datetime import datetime, date, time, timedelta
import json
from threading import Lock
class ObjectCondition:
"""
Represents a single condition to evaluate an attribute of an object
based on a specified comparison operator and value.
Attributes:
_accepted_comp_operators_strings: Operators valid for string comparisons.
_accepted_comp_operators_numbers: Operators valid for numeric comparisons.
_accepted_comp_operators_lists: Operators valid for list-based comparisons.
_accepted_value_types: Supported data types for the condition's attribute value.
"""
_accepted_comp_operators_strings = ("==", "!=", "in", "not in")
_accepted_comp_operators_numbers = ("<", ">", "<=", ">=", "==", "!=")
_accepted_comp_operators_lists = ("in", "not in")
_accepted_comp_operators = tuple(set(_accepted_comp_operators_strings +
_accepted_comp_operators_numbers +
_accepted_comp_operators_lists))
# TODO: add weekdays, monthes to compare & also allowe == and != for these
_accepted_value_types = ("str", "int", "float", "date", "datetime", "time")
def __init__(self, attribute_name: str, comp_operator: str,
attribute_value: str | int | float | date | datetime | time, value_type: str = "str"):
"""
Initializes an ObjectCondition instance with a specified attribute, comparison operator, value, and value type.
:param attribute_name: Name of the attribute to be evaluated on the object.
:param comp_operator: Comparison operator, must be one of the accepted types.
:param attribute_value: The value to compare against.
:param value_type: The type of the attribute, default is 'str'.
"""
if value_type not in self._accepted_value_types:
raise ValueError(f"Value type {value_type} is not accepted. Accepted types: {self._accepted_value_types}")
if comp_operator not in self._accepted_comp_operators:
raise ValueError("Comp operators not supported")
self._value_type = value_type
self._comp_operator: str = comp_operator
self._attribute_name: str = attribute_name
match value_type:
case "str":
if self._comp_operator not in self._accepted_comp_operators_strings:
raise ValueError(f"Comp operator {self._comp_operator} not supported for strings")
self._attribute_value = str(attribute_value)
case "int":
if self._comp_operator not in self._accepted_comp_operators_numbers:
raise ValueError(f"Comp operator {self._comp_operator} not supported for numbers")
self._attribute_value = int(attribute_value)
case "float":
if self._comp_operator not in self._accepted_comp_operators_numbers:
raise ValueError(f"Comp operator {self._comp_operator} not supported for numbers")
self._attribute_value = float(attribute_value)
case "date":
if self._comp_operator not in self._accepted_comp_operators_numbers:
raise ValueError(f"Comp operator {self._comp_operator} not supported for numbers")
self._attribute_value = self.parse_datetime(attribute_value).date()
case "time":
if self._comp_operator not in self._accepted_comp_operators_numbers:
raise ValueError(f"Comp operator {self._comp_operator} not supported for numbers")
self._attribute_value = self.parse_datetime(attribute_value).time()
case "datetime":
if self._comp_operator not in self._accepted_comp_operators_numbers:
raise ValueError(f"Comp operator {self._comp_operator} not supported for numbers")
self._attribute_value = self.parse_datetime(attribute_value)
case _:
raise ValueError(f"Invalid value type {value_type}")
self.lock = Lock()
@property
def attribute_name(self) -> str:
with self.lock:
return self._attribute_name
@property
def comp_operator(self) -> str:
with self.lock:
return self._comp_operator
@property
def attribute_value(self) -> str:
with self.lock:
return str(self._attribute_value)
def is_true(self, obj: object) -> bool:
"""
Evaluates the condition against an attribute of the given object.
:param obj: The object containing the attribute to be checked.
:return: Boolean indicating if the condition holds true for the given object.
"""
if not hasattr(obj, self._attribute_name):
raise AttributeError(f"Condition evaluation error.\nObject ({obj}) has no attribute {self._attribute_name}")
test_value = getattr(obj, self._attribute_name)
if self._value_type == "str":
if not isinstance(test_value, (str, tuple, list, set, frozenset)):
raise TypeError(f"Condition evaluation error.\nObject ({obj}) attribute type {type(test_value)} "
f"is not type (str, tuple, list, set, frozenset)")
elif self._value_type in ("date", "time", "datetime"):
test_value = self.convert_to_type(test_value)
elif not isinstance(test_value, type(self._attribute_value)):
raise TypeError(f"Condition evaluation error.\nObject ({obj}) attribute type {type(test_value)} "
f"is not type {type(self._attribute_value)}")
match self._comp_operator:
# FIXME: seems to not working properly anyhow?
case "in":
if isinstance(test_value, str):
return self._attribute_value.lower() in test_value.lower()
else:
return self._attribute_value.lower() in [item.lower() for item in test_value]
case "not in":
if isinstance(test_value, str):
return self._attribute_value.lower() not in test_value.lower()
else:
return self._attribute_value.lower() not in [item.lower() for item in test_value]
case "<":
return self._attribute_value < test_value
case ">":
return self._attribute_value > test_value
case "<=":
return self._attribute_value <= test_value
case ">=":
return self._attribute_value >= test_value
case "==":
if isinstance(test_value, str):
return test_value.lower() == self._attribute_value.lower()
else:
return test_value == self._attribute_value
case "!=":
if isinstance(test_value, str):
return test_value.lower() != self._attribute_value.lower()
else:
return test_value != self._attribute_value
case _:
raise Exception(f"Unknown comparison operator {self._comp_operator}")
def to_dict(self) -> dict:
"""
Serializes the condition to a dictionary.
:return: A dictionary with the condition's parameters.
"""
with self.lock:
return {
"attribute_name": self._attribute_name,
"comp_operator": self._comp_operator,
"attribute_value": str(self._attribute_value),
"value_type": self._value_type
}
def json(self) -> str:
"""
Serializes the condition to a JSON string.
:return: JSON string representation of the condition.
"""
return json.dumps(self.to_dict())
def convert_to_type(self, input_value):
# Ensure output_type is valid
# Convert input_value to a datetime object first
if isinstance(input_value, datetime):
# Already a datetime, so no conversion needed
dt_value = input_value
elif isinstance(input_value, date):
# Convert date to datetime at midnight
dt_value = datetime.combine(input_value, time(0, 0))
elif isinstance(input_value, time):
# Convert time to datetime on today's date
dt_value = datetime.combine(date.today(), input_value)
elif isinstance(input_value, (int, float)):
# Treat as Unix timestamp
dt_value = datetime.fromtimestamp(input_value)
elif isinstance(input_value, str):
# Try to parse string as ISO format datetime or date
try:
dt_value = datetime.fromisoformat(input_value)
except ValueError:
try:
# If input is date-only format
dt_value = datetime.combine(date.fromisoformat(input_value), time(0, 0))
except ValueError:
raise ValueError("String format not recognized as ISO date or datetime.")
else:
raise TypeError("Unsupported input type. Must be date, time, datetime, float, or string.")
# Convert dt_value to the requested output type
if self._value_type == "date":
return dt_value.date()
elif self._value_type == "time":
return dt_value.time()
elif self._value_type == "datetime":
return dt_value
@classmethod
def from_json(cls, data: str | dict) -> 'ObjectCondition':
"""
Creates an ObjectCondition instance from a JSON string or dictionary.
:param data: A JSON string or dictionary with condition parameters.
:return: ObjectCondition instance initialized with the given data.
"""
if isinstance(data, str):
data = json.loads(data)
elif not isinstance(data, dict):
raise ValueError("Input must be a JSON string or a dictionary.")
return cls(
attribute_name=data["attribute_name"],
comp_operator=data["comp_operator"],
attribute_value=data["attribute_value"],
value_type=data["value_type"]
)
@classmethod
def get_operators_for_string(cls):
return cls._accepted_comp_operators_strings
@classmethod
def get_operators_for_number(cls):
return cls._accepted_comp_operators_numbers
@staticmethod
def parse_datetime(value: str) -> datetime:
"""
Parses a date/time from string or timestamp.
:param value: string with timestamp or date.
:return: datetime object representing the given value.
"""
if value.replace('.', '', 1).isdigit():
timestamp = float(value)
return datetime.fromtimestamp(timestamp)
elif "-" in value and ("T" in value or len(value) == 10):
if len(value) == 10:
return datetime.fromisoformat(value + "T00:00:00")
else:
return datetime.fromisoformat(value)
else:
raise ValueError("Input is not a recognized Unix timestamp or ISO datetime format.")
def __str__(self) -> str:
return f"Condition on {self._attribute_name} {self._comp_operator} {self._attribute_value} ({self._value_type})"
class ConditionList:
"""
Represents a collection of ObjectCondition and ConditionList objects
with a specified logical operator.
Attributes:
_accepted_boolean_operators: Operators valid for combining conditions (and, or).
"""
_accepted_boolean_operators = ("and", "or")
def __init__(self, *conditions, operator: str = "and"):
"""
Initializes a ConditionList with specified conditions and logical operator.
:param conditions: Conditions to be evaluated as a list of ObjectCondition or ConditionList instances.
:param operator: Logical operator to apply across conditions, either 'and' or 'or'.
"""
self.conditions = []
self.lock = Lock()
if operator.lower() not in self._accepted_boolean_operators:
raise ValueError("Operator not supported")
self.operator = operator.lower()
for condition in conditions:
if isinstance(condition, ObjectCondition) or isinstance(condition, ConditionList):
self.conditions.append(condition)
else:
raise ValueError(f"Invalid condition type {type(condition)}")
def add(self, *conditions, operator: str = "and"):
with self.lock:
for condition in conditions:
if isinstance(condition, ObjectCondition) or isinstance(condition, ConditionList):
self.conditions.append(condition)
else:
raise ValueError(f"Invalid condition type {type(condition)}")
def is_true(self, obj: object) -> bool:
"""
Evaluates all conditions in the list using the specified logical operator.
:param obj: Object to check conditions against.
:return: Boolean indicating the result of all combined conditions.
"""
result_list = []
for condition in self.conditions:
result = condition.is_true(obj)
result_list.append(result)
final_result = result_list[0]
for result in result_list[1:]:
if self.operator == "and":
final_result = final_result and result
elif self.operator == "or":
final_result = final_result or result
else:
raise ValueError(f"Unknown operator: {self.operator}")
return final_result
def to_dict(self) -> dict:
"""
Serializes the ConditionList to a dictionary.
:return: A dictionary with 'operator' and 'conditions' keys.
"""
return {
"operator": self.operator,
"conditions": [condition.to_dict() for condition in self.conditions]
}
def json(self) -> str:
"""
Serializes the ConditionList to a JSON string.
:return: JSON string representing the ConditionList.
"""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, data: str | dict) -> 'ConditionList':
"""
Creates a ConditionList instance from a JSON string or dictionary.
:param data: A JSON string or dictionary with 'operator' and 'conditions'.
:return: ConditionList instance populated with the specified conditions and operator.
"""
if isinstance(data, str):
data = json.loads(data)
elif not isinstance(data, dict):
raise ValueError("Input must be a JSON string or a dictionary.")
operator = data.get("operator", "and")
conditions = [
ObjectCondition.from_json(cond) if isinstance(cond, dict) and "attribute_name" in cond else cls.from_json(
cond)
for cond in data.get("conditions", [])
]
return cls(*conditions, operator=operator)
def __str__(self) -> str:
conditions_str = f" {self.operator.upper()} ".join(str(cond) for cond in self.conditions)
return f"ConditionList({conditions_str})"
if __name__ == "__main__":
print("Please start with another module.")