/
has_traits.py
3763 lines (3092 loc) · 136 KB
/
has_traits.py
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (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!
""" Defines the HasTraits class, along with several useful subclasses and
associated metaclasses.
"""
import abc
import copy as copy_module
import inspect
import os
import pickle
import re
import types
import warnings
import weakref
from types import FunctionType
from . import __version__ as TraitsVersion
from .adaptation.adaptation_error import AdaptationError
from .constants import DefaultValue, TraitKind
from .ctrait import CTrait, __newobj__
from .ctraits import CHasTraits
from .observation import api as observe_api
from .traits import (
ForwardProperty,
Property,
Trait,
generic_trait,
)
from .trait_types import Any, Bool, Disallow, Event, Python, Str
from .trait_notifiers import (
ExtendedTraitChangeNotifyWrapper,
FastUITraitChangeNotifyWrapper,
NewTraitChangeNotifyWrapper,
StaticAnytraitChangeNotifyWrapper,
StaticTraitChangeNotifyWrapper,
TraitChangeNotifyWrapper,
ui_dispatch,
)
from .trait_base import (
SequenceTypes,
TraitsCache,
Undefined,
is_none,
not_event,
not_false,
)
from .trait_errors import TraitError
from .util.deprecated import deprecated
from .trait_converters import check_trait, mapped_trait_for, trait_for
# Set CHECK_INTERFACES to one of the following values:
#
# - 0: Does not check to see if classes implement their declared interfaces.
# - 1: Ensures that classes implement the interfaces they say they do, and
# logs a warning if they don't.
# - 2: Ensures that classes implement the interfaces they say they do, and
# raises an InterfaceError if they don't.
#
# This constant is used by the @provides decorator when deciding whether to
# do interface checking. This behaviour is deprecated. In the future, the
# provides decorator will no longer perform interface checking, regardless of
# the value of this constant.
CHECK_INTERFACES = 0
# This ABC is a placeholder for the TraitsUI ViewElement class, which should
# inherit from or register as implementing the API. This has to be done here
# so that the metaclass machinery has something to check against when
# filtering out TraitsUI elements that are declared as part of a HasTraits
# class.
class AbstractViewElement(abc.ABC):
pass
# Constants
WrapperTypes = (
StaticAnytraitChangeNotifyWrapper,
StaticTraitChangeNotifyWrapper,
)
# Class dictionary entries used to save trait, listener and view information
# and definitions:
BaseTraits = "__base_traits__"
ClassTraits = "__class_traits__"
PrefixTraits = "__prefix_traits__"
ListenerTraits = "__listener_traits__"
ObserverTraits = "__observer_traits__"
ViewTraits = "__view_traits__"
InstanceTraits = "__instance_traits__"
# The default Traits View name
DefaultTraitsView = "traits_view"
# Trait types which cannot have default values
CantHaveDefaultValue = ("event", "delegate", "constant")
# The trait types that should be copied last when doing a 'copy_traits':
DeferredCopy = ("delegate", "property")
# Quick test for normal vs extended trait name
extended_trait_pat = re.compile(r".*[ :\+\-,\.\*\?\[\]]")
# Generic 'Any' trait:
any_trait = Any().as_ctrait()
# Mapping from user-facing strings to the dispatcher callable in observe.
_ObserverDispatchers = {
"same": observe_api.dispatch_same,
"ui": ui_dispatch,
}
def _clone_trait(clone, metadata=None):
""" Creates a clone of a specified trait.
"""
trait = CTrait(TraitKind.trait)
trait.clone(clone)
if clone.__dict__ is not None:
trait.__dict__ = clone.__dict__.copy()
if metadata is not None:
trait.__dict__.update(metadata)
return trait
def _get_method(cls, method):
""" Get the definition of a specified method (if any). """
result = getattr(cls, method, None)
if (result is not None) and is_unbound_method_type(result):
return result
return None
def _get_def(class_name, class_dict, bases, method):
""" Gets the definition of a specified method (if any).
"""
if method[0:2] == "__":
# When name-mangling to handle the __ case (for _private traits),
# leading underscores in the class name are stripped out.
method = "_%s%s" % (class_name.lstrip('_'), method)
result = class_dict.get(method)
if (
(result is not None)
and is_unbound_method_type(result)
and (getattr(result, "on_trait_change", None) is None)
and (getattr(result, "_observe_inputs", None) is None)
):
return result
for base in bases:
result = getattr(base, method, None)
if (
(result is not None)
and is_unbound_method_type(result)
and (getattr(result, "on_trait_change", None) is None)
and (getattr(result, "_observe_inputs", None) is None)
):
return result
return None
def is_unbound_method_type(method):
""" Check for something that looks like an unbound class method.
This is used in practice to identify magic-named _name_changed
and _name_fired methods.
"""
# The ismethoddescriptor check catches methods written in C or Cython
# extensions. It excludes things that pass an isfunction check, so we have
# to explicitly re-include that check.
return inspect.isfunction(method) or inspect.ismethoddescriptor(method)
def _is_serializable(value):
""" Returns whether or not a specified value is serializable.
"""
if isinstance(value, (list, tuple)):
for item in value:
if not _is_serializable(item):
return False
return True
if isinstance(value, dict):
for name, item in value.items():
if (not _is_serializable(name)) or (not _is_serializable(item)):
return False
return True
return (not isinstance(value, HasTraits)) or value.has_traits_interface(
ISerializable
)
def _get_instance_handlers(class_dict, bases):
""" Returns a dictionary of potential 'Instance' or 'List(Instance)'
handlers.
"""
# Create the results dictionary:
instance_traits = {}
# Merge all of the base class information into the result:
for base in bases:
for name, base_arg_lists in base.__dict__.get(InstanceTraits).items():
arg_lists = instance_traits.get(name)
if arg_lists is None:
instance_traits[name] = base_arg_lists[:]
else:
for arg_list in base_arg_lists:
if arg_list not in arg_lists:
arg_lists.append(arg_list)
# Merge in the information from the class dictionary:
for name, value in class_dict.items():
if (name[:1] == "_") and is_unbound_method_type(value):
n = 13
col = name.find("_changed_for_")
if col < 2:
n = 11
col = name.find("_fired_for_")
if col >= 2:
key = name[col + n:]
if key != "":
arg_list = (name, name[1:col])
arg_lists = instance_traits.setdefault(key, [])
if arg_list not in arg_lists:
arg_lists.append(arg_list)
# Return the dictionary of possible arg_lists:
return instance_traits
def get_delegate_pattern(name, trait):
""" Returns the correct 'delegate' listener pattern for a specified name
and delegate trait.
"""
prefix = trait._prefix
if prefix == "":
prefix = name
elif (len(prefix) > 1) and (prefix[-1] == "*"):
prefix = prefix[:-1] + name
return " %s:%s" % (trait._delegate, prefix)
class _SimpleTest:
def __init__(self, value):
self.value = value
def __call__(self, test):
return test == self.value
def _add_notifiers(notifiers, handlers):
""" Adds a list of handlers to a specified notifiers list.
"""
for handler in handlers:
if not isinstance(handler, WrapperTypes):
handler = StaticTraitChangeNotifyWrapper(handler)
notifiers.append(handler)
def _add_event_handlers(trait, cls, handlers):
""" Adds any specified event handlers defined for a trait by a class.
"""
events = trait.event
if events is not None:
if isinstance(events, str):
events = [events]
for event in events:
handlers.append(_get_method(cls, "_%s_changed" % event))
handlers.append(_get_method(cls, "_%s_fired" % event))
def _property_method(class_dict, name):
""" Returns the method associated with a particular class property
getter/setter.
"""
return class_dict.get(name)
def _create_property_observe_state(observe, property_name, cached):
""" Create the metadata for setting up an observer for Property.
Parameters
----------
observe : str or list or Expression
As is accepted by HasTraits.observe expression argument
This is the value provided in Property(observe=...)
property_name : str
The name of the property trait.
cached : boolean
Whether the property is cached or not.
Returns
-------
state : dict
State to be used by _init_traits_observers
"""
def handler(instance, event):
if cached:
cache_name = TraitsCache + property_name
old = instance.__dict__.pop(cache_name, Undefined)
else:
old = Undefined
instance.trait_property_changed(property_name, old)
def handler_getter(instance, name):
return types.MethodType(handler, instance)
graphs = _compile_expression(observe)
return dict(
graphs=graphs,
dispatch="same",
handler_getter=handler_getter,
post_init=False,
)
def _compile_expression(expression):
""" Compile a user-supplied expression or list of expressions.
Converts a list of strings or ObserverExpressions to a list of
ObserverGraphs representing the observation patterns to be applied.
Parameters
----------
expression : str or list or ObserverExpression
A description of what traits are being observed.
If this is a list, each item must be a string or an ObserverExpression.
Returns
-------
graphs : list of ObserverGraph
List of graphs representing the observation patterns to be applied
to the relevant objects and handlers.
"""
# Handle the overloaded signature.
# Support list to be consistent with on_trait_change.
if isinstance(expression, list):
expressions = expression
else:
expressions = [expression]
graphs = []
for expr in expressions:
graphs.extend(
observe_api.compile_str(expr) if isinstance(expr, str)
else observe_api.compile_expr(expr)
)
return graphs
# This really should be 'HasTraits', but it's not defined yet:
_HasTraits = None
class MetaHasTraits(type):
""" Controls the creation of HasTraits classes.
The heavy work is done by the `update_traits_class_dict` function, which
takes the ``class_dict`` dictionary of class members and extracts and
processes the trait declarations in it. The trait declarations are then
added back to the class dictionary and passed off to the __new__ method
of the type superclass, to be added to the class.
"""
# All registered class creation listeners.
#
# { Str class_name : Callable listener }
_listeners = {}
def __new__(cls, class_name, bases, class_dict):
update_traits_class_dict(class_name, bases, class_dict)
# Finish building the class using the updated class dictionary:
klass = type.__new__(cls, class_name, bases, class_dict)
# Call all listeners that registered for this specific class:
name = "%s.%s" % (klass.__module__, klass.__name__)
for listener in MetaHasTraits._listeners.get(name, []):
listener(klass)
# Call all listeners that registered for ANY class:
for listener in MetaHasTraits._listeners.get("", []):
listener(klass)
return klass
@classmethod
def add_listener(cls, listener, class_name=""):
""" Adds a class creation listener.
If the class name is the empty string then the listener will be called
when *any* class is created.
.. deprecated:: 6.3.0
"""
warnings.warn(
"add_listener is deprecated", DeprecationWarning, stacklevel=2
)
MetaHasTraits._listeners.setdefault(class_name, []).append(listener)
@classmethod
def remove_listener(cls, listener, class_name=""):
""" Removes a class creation listener.
.. deprecated:: 6.3.0
"""
warnings.warn(
"remove_listener is deprecated", DeprecationWarning, stacklevel=2
)
MetaHasTraits._listeners[class_name].remove(listener)
def update_traits_class_dict(class_name, bases, class_dict):
""" Processes all of the traits related data in the class dictionary.
This is called during the construction of a new HasTraits class. The first
three parameters have the same interpretation as the corresponding
parameters of ``type.__new__``. This function modifies ``class_dict``
in-place.
Parameters
----------
class_name : str
The name of the HasTraits class.
bases : tuple
The base classes for the HasTraits class.
class_dict : dict
A dictionary of class members.
"""
# Create the various class dictionaries, lists and objects needed to
# hold trait and view information and definitions:
base_traits = {}
class_traits = {}
prefix_traits = {}
listeners = {}
prefix_list = []
view_elements = {}
# Mapping from method/trait names to list(dict)
# where each nested dict provides the input arguments for calling
# ``HasTraits.observe`` once. See ``_init_trait_observers``.`
observers = {}
# Create a list of just those base classes that derive from HasTraits:
hastraits_bases = [
base for base in bases if base.__dict__.get(ClassTraits) is not None
]
# Create a list of all inherited trait dictionaries:
inherited_class_traits = [
base.__dict__.get(ClassTraits) for base in hastraits_bases
]
# Move all trait definitions from the class dictionary to the
# appropriate trait class dictionaries:
for name, value in list(class_dict.items()):
value = check_trait(value)
rc = isinstance(value, CTrait)
if (not rc) and isinstance(value, ForwardProperty):
rc = True
# Create Property trait from getter, setter, validator
getter = _property_method(class_dict, "_get_" + name)
setter = _property_method(class_dict, "_set_" + name)
if (setter is None) and (getter is not None):
if getattr(getter, "settable", False):
setter = HasTraits._set_traits_cache
elif getattr(getter, "flushable", False):
setter = HasTraits._flush_traits_cache
validate = _property_method(class_dict, "_validate_" + name)
if validate is None:
validate = value.validate
value = Property(
getter, setter, validate, True, value.handler, **value.metadata
)
if rc:
del class_dict[name]
if name[-1:] != "_":
base_traits[name] = class_traits[name] = value
value_type = value.type
if value_type == "trait":
handler = value.handler
if handler is not None:
if handler.has_items:
items_trait = _clone_trait(
handler.items_event(), value.__dict__
)
if (
items_trait.instance_handler
== "_list_changed_handler"
):
items_trait.instance_handler = (
"_list_items_changed_handler"
)
class_traits[name + "_items"] = items_trait
if handler.is_mapped:
class_traits[name + "_"] = mapped_trait_for(
value, name
)
elif value_type == "delegate":
# Only add a listener if the trait.listenable metadata
# is not False:
if value._listenable is not False:
listeners[name] = (
"delegate",
get_delegate_pattern(name, value),
)
elif value_type == "event":
on_trait_change = value.on_trait_change
if isinstance(on_trait_change, str):
listeners[name] = ("event", on_trait_change)
else:
name = name[:-1]
prefix_list.append(name)
prefix_traits[name] = value
elif is_unbound_method_type(value):
pattern = getattr(value, "on_trait_change", None)
if pattern is not None:
listeners[name] = ("method", pattern)
observer_states = getattr(value, "_observe_inputs", None)
if observer_states is not None:
observers[name] = observer_states
elif isinstance(value, property):
class_traits[name] = generic_trait
# Handle any view elements found in the class:
elif isinstance(value, AbstractViewElement):
view_elements[name] = value
# Remove the view element from the class definition:
del class_dict[name]
else:
for ct in inherited_class_traits:
if name in ct:
# The subclass is providing a default value for the
# trait defined in a superclass.
ictrait = ct[name]
if ictrait.type in CantHaveDefaultValue:
raise TraitError(
"Cannot specify a default value "
"for the %s trait '%s'. You must override the "
"the trait definition instead."
% (ictrait.type, name)
)
class_traits[name] = ictrait(value)
del class_dict[name]
break
# Process all HasTraits base classes:
migrated_properties = {}
for base in hastraits_bases:
base_dict = base.__dict__
# Merge listener information:
for name, value in base_dict.get(ListenerTraits).items():
if (name not in class_traits) and (name not in class_dict):
listeners[name] = value
# Merge observer information:
for name, states in base_dict[ObserverTraits].items():
if (name not in class_traits) and (name not in class_dict):
observers[name] = states
# Merge base traits:
for name, value in base_dict.get(BaseTraits).items():
if name not in base_traits:
property_info = value.property_fields
if property_info is not None:
key = id(value)
migrated_properties[key] = value = migrate_property(
name, value, property_info, class_dict
)
base_traits[name] = value
# Merge class traits:
for name, value in base_dict.get(ClassTraits).items():
if name not in class_traits:
property_info = value.property_fields
if property_info is not None:
new_value = migrated_properties.get(id(value))
if new_value is not None:
value = new_value
else:
value = migrate_property(
name, value, property_info, class_dict
)
class_traits[name] = value
# Merge prefix traits:
base_prefix_traits = base_dict.get(PrefixTraits)
for name in base_prefix_traits["*"]:
if name not in prefix_list:
prefix_list.append(name)
prefix_traits[name] = base_prefix_traits[name]
# Make sure there is a definition for 'undefined' traits:
if prefix_traits.get("") is None:
prefix_list.append("")
prefix_traits[""] = Python().as_ctrait()
# Save a link to the prefix_list:
prefix_traits["*"] = prefix_list
# Make sure the trait prefixes are sorted longest to shortest
# so that we can easily bind dynamic traits to the longest matching
# prefix:
prefix_list.sort(key=len, reverse=True)
# Get the list of all possible 'Instance'/'List(Instance)' handlers:
instance_traits = _get_instance_handlers(class_dict, hastraits_bases)
# If there is an 'anytrait_changed' event handler, wrap it so that
# it can be attached to all traits in the class:
anytrait = _get_def(class_name, class_dict, bases, "_anytrait_changed")
if anytrait is not None:
anytrait = StaticAnytraitChangeNotifyWrapper(anytrait)
# Save it in the prefix traits dictionary so that any dynamically
# created traits (e.g. 'prefix traits') can re-use it:
prefix_traits["@"] = anytrait
# Make one final pass over the class traits dictionary, making sure
# all static trait notification handlers are attached to a 'cloned'
# copy of the original trait:
cloned = set()
for name in list(class_traits.keys()):
trait = class_traits[name]
handlers = [
anytrait,
_get_def(class_name, class_dict, bases, "_%s_changed" % name),
_get_def(class_name, class_dict, bases, "_%s_fired" % name),
]
# Check for an 'Instance' or 'List(Instance)' trait with defined
# handlers:
instance_handler = trait.instance_handler
if (
(instance_handler is not None)
and (name in instance_traits)
or (
(instance_handler == "_list_items_changed_handler")
and (name[-6:] == "_items")
and (name[:-6] in instance_traits)
)
):
handlers.append(getattr(HasTraits, instance_handler))
events = trait.event
if events is not None:
if isinstance(events, str):
events = [events]
for event in events:
handlers.append(
_get_def(
class_name, class_dict, bases, "_%s_changed" % event
)
)
handlers.append(
_get_def(
class_name, class_dict, bases, "_%s_fired" % event
)
)
handlers = [h for h in handlers if h is not None]
default = _get_def(class_name, class_dict, [], "_%s_default" % name)
if (len(handlers) > 0) or (default is not None):
if name not in cloned:
cloned.add(name)
class_traits[name] = trait = _clone_trait(trait)
if len(handlers) > 0:
_add_notifiers(trait._notifiers(True), handlers)
if default is not None:
trait.set_default_value(DefaultValue.callable, default)
# Handle the case of properties whose value depends upon the value
# of other traits:
if (trait.type == "property") and (trait.depends_on is not None):
cached = trait.cached
if cached is True:
cached = TraitsCache + name
depends_on = trait.depends_on
if isinstance(depends_on, SequenceTypes):
depends_on = ",".join(depends_on)
else:
# Note: We add the leading blank to force it to be treated
# as using the extended trait notation so that it will
# automatically add '_items' listeners to lists/dicts:
depends_on = " " + depends_on
listeners[name] = ("property", cached, depends_on)
if trait.type == "property" and trait.observe is not None:
observer_state = _create_property_observe_state(
observe=trait.observe,
property_name=name,
cached=trait.cached,
)
observers[name] = [observer_state]
# Add processed traits back into class_dict.
class_dict[BaseTraits] = base_traits
class_dict[ClassTraits] = class_traits
class_dict[InstanceTraits] = instance_traits
class_dict[PrefixTraits] = prefix_traits
class_dict[ListenerTraits] = listeners
class_dict[ObserverTraits] = observers
class_dict[ViewTraits] = view_elements
def migrate_property(name, property, property_info, class_dict):
""" Migrates an existing property to the class being defined
(allowing for method overrides).
"""
get = _property_method(class_dict, "_get_" + name)
set = _property_method(class_dict, "_set_" + name)
val = _property_method(class_dict, "_validate_" + name)
if (get is not None) or (set is not None) or (val is not None):
old_get, old_set, old_val = property_info
return Property(
get or old_get,
set or old_set,
val or old_val,
True,
**property.__dict__
)
return property
# 'HasTraits' decorators
def observe(expression, *, post_init=False, dispatch="same"):
""" Marks the wrapped method as being a handler to be called when the
specified traits change.
This decorator can be stacked, e.g.::
@observe("attr1")
@observe("attr2", post_init=True)
def updated(self, event):
...
The decorated function must accept one argument which is the event object
representing the change. See :mod:`traits.observation.events` for details.
Parameters
----------
expression : str or list or ObserverExpression
A description of what traits are being observed.
If this is a list, each item must be a string or Expression.
See :py:func:`HasTraits.observe` for details on the
semantics when passing a string.
post_init : boolean, optional
Whether the change handler should be attached after
the state is set when instantiating an object. Default is false, and
values provided to the instance constructor will trigger the
change handler to fire if the value is different from the
default. Set to true to avoid this change event.
dispatch : str, optional
A string indicating how the handler should be run. Default is to run
it on the same thread where the change occurs.
Possible values are:
=========== =======================================================
value dispatch
=========== =======================================================
``same`` Run notifications on the same thread where the change
occurs. The notifications are executed immediately.
``ui`` Run notifications on the UI thread. If the current
thread is the UI thread, the notifications are executed
immediately; otherwise, they are placed on the UI
event queue.
=========== =======================================================
See Also
--------
HasTraits.observe
"""
graphs = _compile_expression(expression)
def observe_decorator(handler):
""" Create input arguments for HasTraits.observe and attach the input
to the callable.
The metaclass will then collect this information for calling
HasTraits.observe with the decorated function.
Parameters
----------
handler : callable
Method of a subclass of HasTraits, with signature of the form
``my_method(self, event)``.
"""
# Warn on a dubious handler signature. The handler should accept a call
# that passes a single positional argument (conventionally named
# "event") in addition to the usual "self".
handler_signature = inspect.signature(handler)
try:
handler_signature.bind("self", "event")
except TypeError:
warnings.warn(
(
"Dubious signature for observe-decorated method. "
"The decorated method should be callable with a "
"single positional argument in addition to 'self'. "
"Did you forget to add an 'event' parameter?"
),
UserWarning,
stacklevel=2,
)
try:
observe_inputs = handler._observe_inputs
except AttributeError:
observe_inputs = []
handler._observe_inputs = observe_inputs
observe_input = dict(
graphs=graphs,
dispatch=dispatch,
post_init=post_init,
handler_getter=getattr,
)
observe_inputs.append(observe_input)
return handler
return observe_decorator
def on_trait_change(name, post_init=False, dispatch="same"):
""" Marks the following method definition as being a handler for the
extended trait change specified by *name(s)*.
Refer to the documentation for the on_trait_change() method of
the **HasTraits** class for information on the correct syntax for
the *name* argument and the semantics of the *dispatch* keyword
argument.
A handler defined using this decorator is normally effective
immediately. However, if *post_init* is **True**, then the handler only
becomes effective after all object constructor arguments have been
processed. That is, trait values assigned as part of object
construction will not cause the handler to be invoked.
See Also
--------
observe : A newer API for defining traits notifications.
"""
def decorator(function):
function.on_trait_change = {
"pattern": name,
"post_init": post_init,
"dispatch": dispatch,
}
return function
return decorator
def cached_property(function):
""" Marks the following method definition as being a "cached property".
That is, it is a property getter which, for performance reasons, caches
its most recently computed result in an attribute whose name is of the
form: *_traits_cache_name*, where *name* is the name of the property. A
method marked as being a cached property needs only to compute and
return its result. The @cached_property decorator automatically wraps
the decorated method in cache management code, eliminating the need to
write boilerplate cache management code explicitly. For example::
file_name = File
file_contents = Property(observe='file_name')
@cached_property
def _get_file_contents(self):
with open(self.file_name, 'rb') as fh:
return fh.read()
In this example, accessing the *file_contents* trait calls the
_get_file_contents() method only once each time after the **file_name**
trait is modified. In all other cases, the cached value
**_file_contents**, which maintained by the @cached_property wrapper
code, is returned.
Note the use, in the example, of the **observe** metadata attribute
to specify that the value of **file_contents** depends on
**file_name**, so that _get_file_contents() is called only when
**file_name** changes. For details, see the traits.traits.Property()
function.
"""
name = TraitsCache + function.__name__[5:]
def decorator(self):
result = self.__dict__.get(name, Undefined)
if result is Undefined:
self.__dict__[name] = result = function(self)
return result
decorator.cached_property = True
return decorator
def property_depends_on(dependency, settable=False, flushable=False):
""" Marks the following method definition as being a "cached property"
that depends on the specified extended trait names. That is, it is a
property getter which, for performance reasons, caches its most
recently computed result in an attribute whose name is of the form:
*_traits_cache_name*, where *name* is the name of the property. A
method marked as being a cached property needs only to compute and
return its result. The @property_depends_on decorator automatically
wraps the decorated method in cache management code that will cache the
most recently computed value and flush the cache when any of the
specified dependencies are modified, thus eliminating the need to write
boilerplate cache management code explicitly. For example::
file_name = File
file_contents = Property
@property_depends_on( 'file_name' )
def _get_file_contents(self):
with open(self.file_name, 'rb') as fh:
return fh.read()
In this example, accessing the *file_contents* trait calls the
_get_file_contents() method only once each time after the **file_name**
trait is modified. In all other cases, the cached value
**_file_contents**, which is maintained by the @cached_property wrapper
code, is returned.
"""
def decorator(function):
name = TraitsCache + function.__name__[5:]
def wrapper(self):
result = self.__dict__.get(name, Undefined)
if result is Undefined:
self.__dict__[name] = result = function(self)
return result
wrapper.cached_property = True
wrapper.depends_on = dependency
wrapper.settable = settable
wrapper.flushable = flushable