File: trait_dict_object.py

package info (click to toggle)
python-traits 6.4.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,648 kB
  • sloc: python: 34,801; ansic: 4,266; makefile: 102
file content (594 lines) | stat: -rw-r--r-- 17,835 bytes parent folder | download
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
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

import copy
import sys
from weakref import ref

from traits.observation.i_observable import IObservable
from traits.trait_base import Undefined, _validate_everything
from traits.trait_errors import TraitError


class TraitDictEvent(object):
    """ An object reporting in-place changes to a traits dict.

    Parameters
    ----------
    removed : dict, optional
        Old keys and values that were just removed.
    added : dict, optional
        New keys and values that were just added.
    changed : dict, optional
        Updated keys and their previous values.

    Attributes
    ----------
    removed : dict
        Old keys and values that were just removed.
    added : dict
        New keys and values that were just added.
    changed : dict
        Updated keys and their previous values.
    """

    def __init__(self, *, removed=None, added=None, changed=None):
        if removed is None:
            removed = {}
        self.removed = removed

        if added is None:
            added = {}
        self.added = added

        if changed is None:
            changed = {}
        self.changed = changed

    def __repr__(self):
        return (
            f"{self.__class__.__name__}("
            f"removed={self.removed!r}, "
            f"added={self.added!r}, "
            f"changed={self.changed!r})"
        )


@IObservable.register
class TraitDict(dict):
    """ A subclass of dict that validates keys and values and notifies
    listeners of any change.

    Parameters
    ----------
    value : dict or iterable, optional
        The initial dict or an iterable containing key-value pairs.
    key_validator : callable, optional
        Called to validate a key in the dict.
        The callable must accept a single key and
        return a validated key or raise a TraitError
        If not provided, all keys are considered valid.
    value_validator : callable, optional
        Called to validate a value in the dict.
        The callable must accept a single value and
        return a validated value or raise a TraitError
        If not provided, all values are considered valid.
    notifiers : list, optional
        A list of callables with the signature::

            notifier(trait_dict, removed, added, changed)

        Where:
        'removed' is a dict of key-values that are no longer in the dictionary.
        'added' is a dict of new key-values that have been added.
        'changed' is a dict with old values previously associated with the key.

    Attributes
    ----------
    key_validator : callable
        Called to validate a key in the dict.
        The callable must accept a single key and
        return a validated key or raise a TraitError
    value_validator : callable
        Called to validate a value in the dict.
        The callable must accept a single value and
        return a validated value or raise a TraitError
    notifiers : list
        A list of callables with the signature::

            notifier(trait_dict, removed, added, changed)

        Where:
        'removed' is a dict of key-values that are no longer in the dictionary.
        'added' is a dict of new key-values that have been added.
        'changed' is a dict with old values previously associated with the key.
    """

    def __new__(cls, *args, **kwargs):
        self = super().__new__(cls)
        self.key_validator = _validate_everything
        self.value_validator = _validate_everything
        self.notifiers = []
        return self

    def __init__(self, value=None, *, key_validator=None,
                 value_validator=None, notifiers=None):

        if key_validator is not None:
            self.key_validator = key_validator

        if value_validator is not None:
            self.value_validator = value_validator

        if notifiers is None:
            notifiers = []
        self.notifiers = notifiers

        if value is None:
            value = {}

        items = value.items() if hasattr(value, 'keys') else value
        value = {self.key_validator(key): self.value_validator(value)
                 for key, value in items}

        super().__init__(value)

    def notify(self, removed, added, changed):
        """ Call all notifiers.

        This simply calls all notifiers provided by the class, if any.
        The notifiers are expected to have the signature::

            notifier(trait_dict, removed, added, changed)

        Any return values are ignored.
        """

        for notifier in self.notifiers:
            notifier(self, removed, added, changed)

    # -- dict interface -------------------------------------------------------

    def __setitem__(self, key, value):
        """ Set a value for the key, implements self[key] = value.

        Parameters
        ----------
        key : A hashable object.
            The key for the value.
        value : any
            The value to set for the corresponding key.
        """

        removed = {}
        validated_key = self.key_validator(key)
        validated_value = self.value_validator(value)

        if validated_key in self:
            changed = {validated_key: self[validated_key]}
            added = {}
        else:
            changed = {}
            added = {validated_key: validated_value}

        super().__setitem__(validated_key, validated_value)
        self.notify(removed=removed, added=added, changed=changed)

    def __delitem__(self, key):
        """ Delete the item from the dict indicated by the key.

        Parameters
        ----------
        key : A hashable object.
            The key to be deleted.

        Raises
        ------
        KeyError
            If the key is not found.
        """

        removed = {key: self[key]} if key in self else {}
        super().__delitem__(key)
        self.notify(removed=removed, added={}, changed={})

    if sys.version_info >= (3, 9):
        def __ior__(self, other):
            """ Update self with the contents of other.

            Parameters
            ----------
            other : mapping or iterable of (key, value) pairs
                Values to be added to this dictionary.
            """
            validated_dict = {}
            added = {}
            changed = {}

            items = other.items() if hasattr(other, 'keys') else other

            for key, value in items:
                validated_key = self.key_validator(key)
                validated_value = self.value_validator(value)

                if validated_key in self:
                    changed[validated_key] = self[validated_key]
                else:
                    added[validated_key] = validated_value

                validated_dict[validated_key] = validated_value

            retval = super().__ior__(validated_dict)

            if added or changed:
                self.notify(removed={}, added=added, changed=changed)

            return retval

    def clear(self):
        """ Remove all items from the dict. """
        was_empty = (self == {})
        removed = self.copy()

        super().clear()
        if not was_empty:
            self.notify(removed=removed, added={}, changed={})

    def update(self, other):
        """ Update the values in the dict by the new dict or an iterable of
        key-value pairs.

        Parameters
        ----------
        other : dict or iterable
            The dict from which values will be updated into this dict.
        """

        validated_dict = {}
        added = {}
        changed = {}

        items = other.items() if hasattr(other, 'keys') else other

        for key, value in items:
            validated_key = self.key_validator(key)
            validated_value = self.value_validator(value)

            if validated_key in self:
                changed[validated_key] = self[validated_key]
            else:
                added[validated_key] = validated_value

            validated_dict[validated_key] = validated_value

        super().update(validated_dict)
        if added or changed:
            self.notify(removed={}, added=added, changed=changed)

    def setdefault(self, key, value=None):
        """ Returns the value if key is present in the dict, else creates the
        key-value pair and returns the value.

        Parameters
        ----------
        key : A hashable object.
            Key to the item.
        """

        if key in self:
            return self[key]

        validated_key = self.key_validator(key)
        validated_value = self.value_validator(value)

        if validated_key in self:
            changed = {validated_key: self[validated_key]}
            added = {}
        else:
            changed = {}
            added = {validated_key: validated_value}

        super().__setitem__(validated_key, validated_value)

        self.notify(removed={}, added=added, changed=changed)

        return validated_value

    def pop(self, key, value=Undefined):
        """ Remove specified key and return the corresponding
        value. If key is not found, the default value is returned
        if given, otherwise KeyError is raised.

        Parameters
        ----------
        key : A hashable object.
            Key to the dict item.

        value : any
            Value to return if key is absent.
        """

        should_notify = (value is Undefined or key in self)
        if value is Undefined:
            removed = super().pop(key)
        else:
            removed = super().pop(key, value)

        if should_notify:
            self.notify(
                removed={key: removed},
                added={},
                changed={}
            )
        return removed

    def popitem(self):
        """ Remove and return some (key, value) pair as a tuple. Raise KeyError
        if dict is empty.

        Returns
        -------
        key_value : tuple
            Some 2-tuple from the dict.

        Raises
        ------
        KeyError
            If the dict is empty
        """

        item = super().popitem()
        self.notify(removed=dict([item]), added={}, changed={})
        return item

    # -- pickle and copy support ----------------------------------------------

    def __getstate__(self):
        """ Get the state of the object for serialization.

        Notifiers are transient and should not be serialized.
        """

        result = self.__dict__.copy()
        # notifiers are transient and should not be serialized
        del result["notifiers"]
        return result

    def __setstate__(self, state):
        """ Restore the state of the object after serialization.

        Notifiers are transient and are restored to the empty list.
        """

        state['notifiers'] = []
        self.__dict__.update(state)

    def __deepcopy__(self, memo):
        """ Perform a deepcopy operation.

        Notifiers are transient and should not be copied.
        """

        result = TraitDict(
            dict(copy.deepcopy(x, memo) for x in self.items()),
            key_validator=copy.deepcopy(self.key_validator, memo),
            value_validator=copy.deepcopy(self.value_validator, memo),
            notifiers=[]
        )
        return result

    # -- Implement IObservable ------------------------------------------------

    def _notifiers(self, force_create):
        """ Return a list of callables where each callable is a notifier.
        The list is expected to be mutated for contributing or removing
        notifiers from the object.

        Parameters
        ----------
        force_create: boolean
            Not used here.
        """
        return self.notifiers


class TraitDictObject(TraitDict):
    """ A subclass of TraitDict that fires trait events when mutated.
    This is for backward compatibility with Traits 6.0 and lower.

    This is used by the Dict trait type, and all values set into a Dict
    trait will be copied into a new TraitDictObject instance.

    Mutation of the TraitDictObject will fire a "name_items" event with
    appropriate added, changed and removed values.

    Parameters
    ----------
    trait : CTrait instance
        The CTrait instance associated with the attribute that this dict
        has been set to.
    object : HasTraits
        The object this dict belongs to. Can also be None in cases where the
        dict has been disconnected from its HasTraits parent.
    name : str
        The name of the attribute on the object.
    value : dict
        The dict of values to initialize the TraitDictObject with.

    Attributes
    ----------
    trait : CTrait instance
        The CTrait instance associated with the attribute that this dict
        has been set to.
    object : callable
        A callable that when called with no arguments returns the HasTraits
        object that this dict belongs to, or None if there is no such object.
    name : str
        The name of the attribute on the object.
    name_items : str
        The name of the items event trait that the trait dict will fire when
        mutated.
    """

    def __init__(self, trait, object, name, value):
        self.trait = trait
        self.object = (lambda: None) if object is None else ref(object)
        self.name = name
        self.name_items = None
        if trait.has_items:
            self.name_items = name + "_items"

        super().__init__(value, key_validator=self._key_validator,
                         value_validator=self._value_validator,
                         notifiers=[self.notifier])

    def _key_validator(self, key):
        """ Key validator based on the Dict's key_trait.

        Parameters
        ----------
        key : A hashable object.
            The key to validate.

        Returns
        -------
        validated_key : A hashable object.
            The validated key.

        Raises
        ------
        TraitError
            If the validation fails.
        """

        trait = getattr(self, 'trait', None)
        object = getattr(self, 'object', lambda: None)()

        # Deserialized TraitDictObjects without 'trait' and 'object' set
        # will not validate its keys
        if trait is None or object is None:
            return key

        validate = trait.key_trait.validate
        if validate is None:
            return key

        try:
            return validate(object, self.name, key)
        except TraitError as excep:
            excep.set_prefix("Each key of the")
            raise excep

    def _value_validator(self, value):
        """ Value validator based on the Dict's value_trait.

        Parameters
        ----------
        value : any
            The value to validate.

        Returns
        -------
        validated_value : any
            The validated value.

        Raises
        ------
        TraitError
            If the validation fails.
        """

        trait = getattr(self, 'trait', None)
        object = getattr(self, 'object', lambda: None)()

        # Deserialized TraitDictObjects without 'trait' and 'object' set
        # will not validate its values
        if trait is None or object is None:
            return value

        validate = trait.value_trait.validate
        if validate is None:
            return value

        try:
            return validate(object, self.name, value)
        except TraitError as excep:
            excep.set_prefix("Each value of the")
            raise excep

    def notifier(self, trait_dict, removed, added, changed):
        """ Fire the TraitDictEvent with the provided parameters.

        Parameters
        ----------
        trait_dict : dict
            The complete dictionary.
        removed : dict
            Dict of removed items.
        added : dict
            Dict of added items.
        changed : dict
            Dict of changed items.
        """

        if self.name_items is None:
            return

        object = self.object()

        if object is None:
            return

        if getattr(object, self.name) is not self:
            # Workaround having this dict inside another container which
            # also uses the name_items trait for notification.
            # See enthought/traits#25
            return

        event = TraitDictEvent(removed=removed, added=added, changed=changed)
        items_event = self.trait.items_event()
        object.trait_items_event(self.name_items, event, items_event)

    # -- pickle and copy support ----------------------------------------------

    def __getstate__(self):
        """ Get the state of the object for serialization.

        Object and trait should not be serialized.
        """

        result = super().__getstate__()
        del result["object"]
        del result["trait"]
        return result

    def __setstate__(self, state):
        """ Restore the state of the object after serialization.
        """

        state.setdefault("name", "")
        state["notifiers"] = [self.notifier]
        state["object"] = lambda: None
        state['trait'] = None
        self.__dict__.update(state)

    def __deepcopy__(self, memo):
        """ Perform a deepcopy operation..

        Object is a weakref and should not be copied.
        """
        result = TraitDictObject(
            self.trait,
            None,
            self.name,
            dict(copy.deepcopy(x, memo) for x in self.items()),
        )

        return result