Repository navigation
Expand file tree
/
Copy pathselv.py
More file actions
687 lines (588 loc) · 24.9 KB
/
Copy pathselv.py
File metadata and controls
687 lines (588 loc) · 24.9 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
"""Python decorator for logging attribute changes."""
__all__ = ["selv"]
import copy
from datetime import datetime
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
SupportsIndex,
Type,
TypeVar,
Union,
)
T = TypeVar("T", bound=Any)
class ObservableDict(dict):
"""Dictionary that notifies parent of changes."""
def __init__(self, *args, parent=None, attr_name=None, **kwargs):
self._parent = parent
self._attr_name = attr_name
self._initializing = True
super().__init__()
if len(args) > 0:
if len(args) > 1:
raise TypeError("expected at most 1 argument, got %d" % len(args))
first_arg = args[0]
for key, value in dict(first_arg).items():
self[key] = value
for key, value in kwargs.items():
self[key] = value
self._initializing = False
def __setitem__(self, key, value):
old_container_state = self.copy() if self._parent else None
wrapped_value = self._wrap_value(value)
super().__setitem__(key, wrapped_value)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def _wrap_value(self, value):
"""Wrap container values for observation."""
# Recursively wrap nested containers to maintain observation chain
if isinstance(value, dict):
return ObservableDict(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, list):
return ObservableList(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, set):
return ObservableSet(value, parent=self._parent, attr_name=self._attr_name)
return value
def __delitem__(self, key):
old_container_state = self.copy() if self._parent else None
super().__delitem__(key)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
class ObservableList(list):
"""List that notifies parent of changes."""
def __init__(self, *args, parent=None, attr_name=None, **kwargs):
self._parent = parent
self._attr_name = attr_name
self._initializing = True
super().__init__()
if len(args) > 0:
first_arg = args[0]
for value in first_arg:
self.append(value)
self._initializing = False
def __setitem__(self, key, value):
old_container_state = self.copy() if self._parent else None
wrapped_value = self._wrap_value(value)
super().__setitem__(key, wrapped_value)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def _wrap_value(self, value):
"""Wrap container values for observation."""
# Recursively wrap nested containers to maintain observation chain
if isinstance(value, dict):
return ObservableDict(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, list):
return ObservableList(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, set):
return ObservableSet(value, parent=self._parent, attr_name=self._attr_name)
return value
def __delitem__(self, key):
old_container_state = self.copy() if self._parent else None
super().__delitem__(key)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def append(self, value):
old_container_state = self.copy() if self._parent else None
wrapped_value = self._wrap_value(value)
super().append(wrapped_value)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def pop(self, index: SupportsIndex = -1):
old_container_state = self.copy() if self._parent else None
result = super().pop(index)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
return result
class ObservableSet(set):
"""Set that notifies parent of changes."""
def __init__(self, *args, parent=None, attr_name=None, **kwargs):
self._parent = parent
self._attr_name = attr_name
self._initializing = True
super().__init__()
if len(args) > 0:
first_arg = args[0]
for value in first_arg:
self.add(value)
self._initializing = False
def add(self, element):
old_container_state = self.copy() if self._parent else None
wrapped_element = self._wrap_value(element)
super().add(wrapped_element)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def _wrap_value(self, value):
"""Wrap container values for observation."""
# Recursively wrap nested containers to maintain observation chain
if isinstance(value, dict):
return ObservableDict(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, list):
return ObservableList(value, parent=self._parent, attr_name=self._attr_name)
elif isinstance(value, set):
return ObservableSet(value, parent=self._parent, attr_name=self._attr_name)
return value
def remove(self, element):
old_container_state = self.copy() if self._parent else None
super().remove(element)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def discard(self, element):
old_container_state = self.copy() if self._parent else None
super().discard(element)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def pop(self):
old_container_state = self.copy() if self._parent else None
result = super().pop()
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
return result
def clear(self):
old_container_state = self.copy() if self._parent else None
super().clear()
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def update(self, *others):
old_container_state = self.copy() if self._parent else None
super().update(*others)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def intersection_update(self, *others):
old_container_state = self.copy() if self._parent else None
super().intersection_update(*others)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def difference_update(self, *others):
old_container_state = self.copy() if self._parent else None
super().difference_update(*others)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
def symmetric_difference_update(self, other):
old_container_state = self.copy() if self._parent else None
super().symmetric_difference_update(other)
if self._parent and self._attr_name and not self._initializing:
new_container_state = self.copy()
self._parent._selv_log_container_change(
self._attr_name, old_container_state, new_container_state
)
class _ChangeRecord:
"""Record of a single attribute change."""
def __init__(
self,
timestamp: datetime,
attribute: str,
old_value: Any,
new_value: Any,
container_key: Optional[Union[str, int]] = None,
):
self.timestamp = timestamp
self.attribute = attribute
self.old_value = old_value
self.new_value = new_value
self.container_key = container_key
def __repr__(self) -> str:
if self.container_key is not None:
if isinstance(self.container_key, int):
attr_str = f"{self.attribute}[{self.container_key}]"
else:
attr_str = f"{self.attribute}['{self.container_key}']"
else:
attr_str = self.attribute
if self.old_value is None and self.new_value is not None:
return f"{attr_str} = {self._format_value(self.new_value)}"
elif self.new_value is None:
return f"{attr_str}: {self._format_value(self.old_value)} -> deleted"
else:
old_val = self._format_value(self.old_value)
new_val = self._format_value(self.new_value)
return f"{attr_str}: {old_val} -> {new_val}"
def _format_value(self, value: Any) -> str:
"""Format value for display."""
if value is None:
return "None"
elif isinstance(value, str):
return f"'{value}'"
elif isinstance(value, (int, float, bool)):
return str(value)
elif isinstance(value, dict):
return self._format_dict(value)
elif isinstance(value, list):
return self._format_list(value)
elif isinstance(value, tuple):
return self._format_tuple(value)
elif isinstance(value, set):
return self._format_set(value)
else:
return f"{type(value).__name__} instance"
def _format_dict(self, value: dict) -> str:
"""Format dictionary value."""
items = []
for k, v in value.items():
if isinstance(k, str):
items.append(f"'{k}': {self._format_value(v)}")
else:
items.append(f"{k}: {self._format_value(v)}")
return "{" + ", ".join(items) + "}"
def _format_list(self, value: list) -> str:
"""Format list value."""
items = [self._format_value(item) for item in value]
return "[" + ", ".join(items) + "]"
def _format_tuple(self, value: tuple) -> str:
"""Format tuple value."""
items = [self._format_value(item) for item in value]
return "(" + ", ".join(items) + ")"
def _format_set(self, value: set) -> str:
"""Format set value."""
# Try to sort for consistent output, fall back to natural order if sorting fails
try:
sorted_items = sorted(value)
except TypeError:
sorted_items = list(value)
items = [self._format_value(item) for item in sorted_items]
return "{" + ", ".join(items) + "}"
class _SelvDecorator:
"""Internal class to handle selv decorator logic."""
def __init__(
self,
track_private: bool = True,
logger: Optional[Callable[[str], None]] = None,
exclude: Optional[List[str]] = None,
actions: Optional[Dict[str, Callable[[Any], None]]] = None,
):
self.track_private = track_private
self.logger = logger
self.exclude = exclude or []
self.actions = actions or {}
def wrap_container(self, self_obj: Any, name: str, value: Any) -> Any:
"""Wrap dict/list/set values."""
# Convert regular containers to observable versions for tracking
if isinstance(value, dict):
return ObservableDict(value, parent=self_obj, attr_name=name)
elif isinstance(value, list):
return ObservableList(value, parent=self_obj, attr_name=name)
elif isinstance(value, set):
return ObservableSet(value, parent=self_obj, attr_name=name)
return value
def _safe_copy(self, value: Any) -> Any:
"""Safely copy a value, handling observable containers specially."""
# Observable containers need special handling to avoid triggering notifications
if value is None:
return None
if isinstance(value, (ObservableDict, ObservableList, ObservableSet)):
if isinstance(value, ObservableDict):
return dict(value.items())
elif isinstance(value, ObservableList):
return list(value)
elif isinstance(value, ObservableSet):
return set(value)
return copy.deepcopy(value)
def _ensure_history_initialized(self, self_obj: Any, name: str) -> None:
"""Ensure change history is initialized for the object and attribute."""
if not hasattr(self_obj, "_selv_change_history"):
self_obj._selv_change_history = {}
if name not in self_obj._selv_change_history:
self_obj._selv_change_history[name] = []
def _log_change_message(
self,
cls_name: str,
attr_str: str,
old_value: Any,
new_value: Any,
is_initial: bool,
log_func: Callable,
record: _ChangeRecord,
) -> None:
"""Log the actual change message."""
# Handle three cases: initialization, deletion, and regular update
if is_initial:
formatted_val = record._format_value(new_value)
log_func(f"[{cls_name}] {attr_str} = {formatted_val} (initialized)")
elif new_value is None:
formatted_old = record._format_value(old_value)
log_func(f"[{cls_name}] {attr_str}: {formatted_old} -> deleted")
else:
formatted_old = record._format_value(old_value)
formatted_new = record._format_value(new_value)
log_func(f"[{cls_name}] {attr_str}: {formatted_old} -> {formatted_new}")
def log_change(
self,
self_obj: Any,
cls_name: str,
name: str,
old_value: Any,
new_value: Any,
container_key: Optional[Union[str, int]] = None,
is_initial: bool = False,
) -> None:
"""Log attribute change."""
self._ensure_history_initialized(self_obj, name)
old_value_copy = self._safe_copy(old_value)
new_value_copy = self._safe_copy(new_value)
record = _ChangeRecord(
timestamp=datetime.now(),
attribute=name,
old_value=old_value_copy,
new_value=new_value_copy,
container_key=container_key,
)
self_obj._selv_change_history[name].append(record)
attr_str = self._get_attribute_string(name, container_key)
log_func = self.logger if self.logger is not None else print
self._log_change_message(
cls_name, attr_str, old_value, new_value, is_initial, log_func, record
)
# Call custom action if defined for this attribute
if name in self.actions:
try:
self.actions[name](new_value)
except Exception as e:
if self.logger is not None:
self.logger(f"Error in custom action for {name}: {e}")
log_func(f"[{cls_name}] Error in action for {attr_str}: {e}")
def _get_attribute_string(
self, name: str, container_key: Optional[Union[str, int]]
) -> str:
"""Get formatted attribute string."""
if container_key is not None:
if isinstance(container_key, int):
return f"{name}[{container_key}]"
else:
return f"{name}['{container_key}']"
return name
def log_container_change(
self,
self_obj: Any,
cls_name: str,
attr_name: str,
old_container_state: Any,
new_container_state: Any,
) -> None:
"""Log container change."""
# Use deepcopy to capture container state at time of change
# This prevents mutations from affecting historical records
old_copy = (
copy.deepcopy(old_container_state)
if old_container_state is not None
else None
)
new_copy = (
copy.deepcopy(new_container_state)
if new_container_state is not None
else None
)
self.log_change(self_obj, cls_name, attr_name, old_copy, new_copy)
def create_setattr(
self, cls: Type[T], original_setattr: Optional[Callable]
) -> Callable:
"""Create the __setattr__ method for the decorated class."""
def new_setattr(self_obj: Any, name: str, value: Any) -> None:
# Skip tracking for private attributes or excluded names
if self._should_skip_tracking(name):
self._set_attribute(self_obj, name, value, original_setattr)
return
has_old_value = hasattr(self_obj, name)
old_value = getattr(self_obj, name, None) if has_old_value else None
# Wrap containers to enable nested tracking
wrapped_value = self.wrap_container(self_obj, name, value)
self._set_attribute(self_obj, name, wrapped_value, original_setattr)
self.log_change(
self_obj,
cls.__name__,
name,
old_value,
wrapped_value,
is_initial=not has_old_value,
)
return new_setattr
def _should_skip_tracking(self, name: str) -> bool:
"""Check if an attribute should be skipped for tracking."""
# Skip private attributes unless tracking is enabled
if name.startswith("_") and not self.track_private:
return True
# Skip internal selv attributes
if name.startswith("_selv_"):
return True
# Skip explicitly excluded attributes
if name in self.exclude:
return True
return False
def _set_attribute(
self,
self_obj: Any,
name: str,
value: Any,
original_setattr: Optional[Callable],
) -> None:
"""Set an attribute using the appropriate setattr method."""
# Use the class's original __setattr__ if available, otherwise use object's
if original_setattr:
original_setattr(self_obj, name, value)
else:
object.__setattr__(self_obj, name, value)
def create_view_changelog(self) -> Callable:
"""Create the view_changelog method for the decorated class."""
def view_changelog(
self_obj: Any,
attribute: Optional[str] = None,
format: Literal["flat", "attr"] = "flat",
) -> Union[Dict[str, List[Dict[str, Any]]], List[Dict[str, Any]]]:
"""View changelog for attributes."""
# Validate format parameter
if format not in ("flat", "attr"):
raise ValueError(f"format must be 'flat' or 'attr', got {format!r}")
if not hasattr(self_obj, "_selv_change_history"):
return self._get_empty_history(attribute, format)
if attribute is None:
return self._get_all_history(self_obj, format)
else:
return self._get_attribute_history(self_obj, attribute)
return view_changelog
def _get_empty_history(
self, attribute: Optional[str], format: Literal["flat", "attr"]
) -> Union[Dict[str, List[Dict[str, Any]]], List[Dict[str, Any]]]:
"""Return empty history when no change history exists."""
if attribute is None:
return [] if format == "flat" else {}
return []
def _get_all_history(
self, self_obj: Any, format: Literal["flat", "attr"]
) -> Union[Dict[str, List[Dict[str, Any]]], List[Dict[str, Any]]]:
"""Get history for all attributes."""
if format == "flat":
return self._get_all_history_flat(self_obj)
else:
return self._get_all_history_attr(self_obj)
def _get_all_history_flat(self, self_obj: Any) -> List[Dict[str, Any]]:
"""Get flat format history for all attributes."""
result = []
for attr_name, records in self_obj._selv_change_history.items():
for record in records:
result.append(self._format_record(record, attr_name))
return result
def _get_all_history_attr(self, self_obj: Any) -> Dict[str, List[Dict[str, Any]]]:
"""Get attribute format history for all attributes."""
result = {}
for attr_name, records in self_obj._selv_change_history.items():
result[attr_name] = [self._format_record(record) for record in records]
return result
def _get_attribute_history(
self, self_obj: Any, attribute: str
) -> List[Dict[str, Any]]:
"""Get history for a specific attribute."""
records = self_obj._selv_change_history.get(attribute, [])
return [self._format_record(record) for record in records]
def _format_record(
self, record: _ChangeRecord, attr_name: Optional[str] = None
) -> Dict[str, Any]:
"""Format a single change record."""
formatted = {
"time": record.timestamp,
"from": record.old_value,
"to": record.new_value,
}
if attr_name is not None:
formatted["attr"] = attr_name
return formatted
def _selv(
track_private: bool = True,
logger: Optional[Callable[[str], None]] = None,
exclude: Optional[List[str]] = None,
actions: Optional[Dict[str, Callable[[Any], None]]] = None,
) -> Any:
"""Class decorator for logging attribute changes."""
def decorator(cls: Type[T]) -> Any:
decorator_instance = _SelvDecorator(track_private, logger, exclude, actions)
original_setattr = getattr(cls, "__setattr__", None)
# Create bound methods for the class
def wrap_container(self_obj: Any, name: str, value: Any) -> Any:
return decorator_instance.wrap_container(self_obj, name, value)
def log_change(
self_obj: Any,
name: str,
old_value: Any,
new_value: Any,
container_key: Optional[Union[str, int]] = None,
is_initial: bool = False,
) -> None:
decorator_instance.log_change(
self_obj,
cls.__name__,
name,
old_value,
new_value,
container_key,
is_initial,
)
def log_container_change(
self_obj: Any,
attr_name: str,
old_container_state: Any,
new_container_state: Any,
) -> None:
decorator_instance.log_container_change(
self_obj,
cls.__name__,
attr_name,
old_container_state,
new_container_state,
)
# Attach methods to the decorated class
cls.__setattr__ = decorator_instance.create_setattr(cls, original_setattr)
cls.view_changelog = decorator_instance.create_view_changelog()
cls._selv_wrap_container = wrap_container
cls._selv_log_change = log_change
cls._selv_log_container_change = log_container_change
return cls
return decorator
def selv_decorator(*args: Any, **kwargs: Any) -> Any:
"""Decorator for @selv and @selv(...) syntax."""
if args and not kwargs and callable(args[0]):
return _selv()(args[0])
return _selv(*args, **kwargs)
selv = selv_decorator