-
-
Notifications
You must be signed in to change notification settings - Fork 198
/
traitlets.py
3487 lines (2866 loc) · 117 KB
/
traitlets.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
"""
A lightweight Traits like module.
This is designed to provide a lightweight, simple, pure Python version of
many of the capabilities of enthought.traits. This includes:
* Validation
* Type specification with defaults
* Static and dynamic notification
* Basic predefined types
* An API that is similar to enthought.traits
We don't support:
* Delegation
* Automatic GUI generation
* A full set of trait types. Most importantly, we don't provide container
traits (list, dict, tuple) that can trigger notifications if their
contents change.
* API compatibility with enthought.traits
There are also some important difference in our design:
* enthought.traits does not validate default values. We do.
We choose to create this module because we need these capabilities, but
we need them to be pure Python so they work in all Python implementations,
including Jython and IronPython.
Inheritance diagram:
.. inheritance-diagram:: traitlets.traitlets
:parts: 3
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
#
# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
# also under the terms of the Modified BSD License.
import contextlib
import enum
import inspect
import os
import re
import sys
import types
import typing as t
from ast import literal_eval
from warnings import warn, warn_explicit
from .utils.bunch import Bunch
from .utils.descriptions import add_article, class_of, describe, repr_type
from .utils.getargspec import getargspec
from .utils.importstring import import_item
from .utils.sentinel import Sentinel
SequenceTypes = (list, tuple, set, frozenset)
# backward compatibility, use to differ between Python 2 and 3.
ClassTypes = (type,)
# exports:
__all__ = [
"All",
"Any",
"BaseDescriptor",
"Bool",
"Bytes",
"CBool",
"CBytes",
"CComplex",
"CFloat",
"CInt",
"CLong",
"CRegExp",
"CUnicode",
"Callable",
"CaselessStrEnum",
"ClassBasedTraitType",
"Complex",
"Container",
"DefaultHandler",
"Dict",
"DottedObjectName",
"Enum",
"EventHandler",
"Float",
"ForwardDeclaredInstance",
"ForwardDeclaredMixin",
"ForwardDeclaredType",
"FuzzyEnum",
"HasDescriptors",
"HasTraits",
"Instance",
"Int",
"Integer",
"List",
"Long",
"MetaHasDescriptors",
"MetaHasTraits",
"ObjectName",
"ObserveHandler",
"Set",
"TCPAddress",
"This",
"TraitError",
"TraitType",
"Tuple",
"Type",
"Unicode",
"Undefined",
"Union",
"UseEnum",
"ValidateHandler",
"default",
"directional_link",
"dlink",
"link",
"observe",
"observe_compat",
"parse_notifier_name",
"validate",
]
# any TraitType subclass (that doesn't start with _) will be added automatically
# -----------------------------------------------------------------------------
# Basic classes
# -----------------------------------------------------------------------------
Undefined = Sentinel(
"Undefined",
"traitlets",
"""
Used in Traitlets to specify that no defaults are set in kwargs
""",
)
All = Sentinel(
"All",
"traitlets",
"""
Used in Traitlets to listen to all types of notification or to notifications
from all trait attributes.
""",
)
# Deprecated alias
NoDefaultSpecified = Undefined
class TraitError(Exception):
pass
# -----------------------------------------------------------------------------
# Utilities
# -----------------------------------------------------------------------------
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
def isidentifier(s):
return s.isidentifier()
_deprecations_shown = set()
def _should_warn(key):
"""Add our own checks for too many deprecation warnings.
Limit to once per package.
"""
env_flag = os.environ.get("TRAITLETS_ALL_DEPRECATIONS")
if env_flag and env_flag != "0":
return True
if key not in _deprecations_shown:
_deprecations_shown.add(key)
return True
else:
return False
def _deprecated_method(method, cls, method_name, msg):
"""Show deprecation warning about a magic method definition.
Uses warn_explicit to bind warning to method definition instead of triggering code,
which isn't relevant.
"""
warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
classname=cls.__name__, method_name=method_name, msg=msg
)
for parent in inspect.getmro(cls):
if method_name in parent.__dict__:
cls = parent
break
# limit deprecation messages to once per package
package_name = cls.__module__.split(".", 1)[0]
key = (package_name, msg)
if not _should_warn(key):
return
try:
fname = inspect.getsourcefile(method) or "<unknown>"
lineno = inspect.getsourcelines(method)[1] or 0
except (OSError, TypeError) as e:
# Failed to inspect for some reason
warn(warn_msg + ("\n(inspection failed) %s" % e), DeprecationWarning)
else:
warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
def _safe_literal_eval(s):
"""Safely evaluate an expression
Returns original string if eval fails.
Use only where types are ambiguous.
"""
try:
return literal_eval(s)
except (NameError, SyntaxError, ValueError):
return s
def is_trait(t):
"""Returns whether the given value is an instance or subclass of TraitType."""
return isinstance(t, TraitType) or (isinstance(t, type) and issubclass(t, TraitType))
def parse_notifier_name(names):
"""Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name([])
[traitlets.All]
>>> parse_notifier_name("a")
['a']
>>> parse_notifier_name(["a", "b"])
['a', 'b']
>>> parse_notifier_name(All)
[traitlets.All]
"""
if names is All or isinstance(names, str):
return [names]
else:
if not names or All in names:
return [All]
for n in names:
if not isinstance(n, str):
raise TypeError("names must be strings, not %r" % n)
return names
class _SimpleTest:
def __init__(self, value):
self.value = value
def __call__(self, test):
return test == self.value
def __repr__(self):
return "<SimpleTest(%r)" % self.value
def __str__(self):
return self.__repr__()
def getmembers(object, predicate=None):
"""A safe version of inspect.getmembers that handles missing attributes.
This is useful when there are descriptor based attributes that for
some reason raise AttributeError even though they exist. This happens
in zope.inteface with the __provides__ attribute.
"""
results = []
for key in dir(object):
try:
value = getattr(object, key)
except AttributeError:
pass
else:
if not predicate or predicate(value):
results.append((key, value))
results.sort()
return results
def _validate_link(*tuples):
"""Validate arguments for traitlet link functions"""
for tup in tuples:
if not len(tup) == 2:
raise TypeError(
"Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t
)
obj, trait_name = tup
if not isinstance(obj, HasTraits):
raise TypeError("Each object must be HasTraits, not %r" % type(obj))
if trait_name not in obj.traits():
raise TypeError(f"{obj!r} has no trait {trait_name!r}")
class link:
"""Link traits from different objects together so they remain in sync.
Parameters
----------
source : (object / attribute name) pair
target : (object / attribute name) pair
transform: iterable with two callables (optional)
Data transformation between source and target and target and source.
Examples
--------
>>> class X(HasTraits):
... value = Int()
>>> src = X(value=1)
>>> tgt = X(value=42)
>>> c = link((src, "value"), (tgt, "value"))
Setting source updates target objects:
>>> src.value = 5
>>> tgt.value
5
"""
updating = False
def __init__(self, source, target, transform=None):
_validate_link(source, target)
self.source, self.target = source, target
self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2
self.link()
def link(self):
try:
setattr(
self.target[0],
self.target[1],
self._transform(getattr(self.source[0], self.source[1])),
)
finally:
self.source[0].observe(self._update_target, names=self.source[1])
self.target[0].observe(self._update_source, names=self.target[1])
@contextlib.contextmanager
def _busy_updating(self):
self.updating = True
try:
yield
finally:
self.updating = False
def _update_target(self, change):
if self.updating:
return
with self._busy_updating():
setattr(self.target[0], self.target[1], self._transform(change.new))
if getattr(self.source[0], self.source[1]) != change.new:
raise TraitError(
"Broken link {}: the source value changed while updating "
"the target.".format(self)
)
def _update_source(self, change):
if self.updating:
return
with self._busy_updating():
setattr(self.source[0], self.source[1], self._transform_inv(change.new))
if getattr(self.target[0], self.target[1]) != change.new:
raise TraitError(
"Broken link {}: the target value changed while updating "
"the source.".format(self)
)
def unlink(self):
self.source[0].unobserve(self._update_target, names=self.source[1])
self.target[0].unobserve(self._update_source, names=self.target[1])
class directional_link:
"""Link the trait of a source object with traits of target objects.
Parameters
----------
source : (object, attribute name) pair
target : (object, attribute name) pair
transform: callable (optional)
Data transformation between source and target.
Examples
--------
>>> class X(HasTraits):
... value = Int()
>>> src = X(value=1)
>>> tgt = X(value=42)
>>> c = directional_link((src, "value"), (tgt, "value"))
Setting source updates target objects:
>>> src.value = 5
>>> tgt.value
5
Setting target does not update source object:
>>> tgt.value = 6
>>> src.value
5
"""
updating = False
def __init__(self, source, target, transform=None):
self._transform = transform if transform else lambda x: x
_validate_link(source, target)
self.source, self.target = source, target
self.link()
def link(self):
try:
setattr(
self.target[0],
self.target[1],
self._transform(getattr(self.source[0], self.source[1])),
)
finally:
self.source[0].observe(self._update, names=self.source[1])
@contextlib.contextmanager
def _busy_updating(self):
self.updating = True
try:
yield
finally:
self.updating = False
def _update(self, change):
if self.updating:
return
with self._busy_updating():
setattr(self.target[0], self.target[1], self._transform(change.new))
def unlink(self):
self.source[0].unobserve(self._update, names=self.source[1])
dlink = directional_link
# -----------------------------------------------------------------------------
# Base Descriptor Class
# -----------------------------------------------------------------------------
class BaseDescriptor:
"""Base descriptor class
Notes
-----
This implements Python's descriptor protocol.
This class is the base class for all such descriptors. The
only magic we use is a custom metaclass for the main :class:`HasTraits`
class that does the following:
1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
instance in the class dict to the name of the attribute.
2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
instance in the class dict to the *class* that declared the trait.
This is used by the :class:`This` trait to allow subclasses to
accept superclasses for :class:`This` values.
"""
name: t.Optional[str] = None
this_class: t.Optional[t.Type[t.Any]] = None
def class_init(self, cls, name):
"""Part of the initialization which may depend on the underlying
HasDescriptors class.
It is typically overloaded for specific types.
This method is called by :meth:`MetaHasDescriptors.__init__`
passing the class (`cls`) and `name` under which the descriptor
has been assigned.
"""
self.this_class = cls
self.name = name
def subclass_init(self, cls):
pass
def instance_init(self, obj):
"""Part of the initialization which may depend on the underlying
HasDescriptors instance.
It is typically overloaded for specific types.
This method is called by :meth:`HasTraits.__new__` and in the
:meth:`BaseDescriptor.instance_init` method of descriptors holding
other descriptors.
"""
pass
class TraitType(BaseDescriptor):
"""A base class for all trait types."""
metadata: t.Dict[str, t.Any] = {}
allow_none = False
read_only = False
info_text = "any value"
default_value: t.Optional[t.Any] = Undefined
def __init__(
self,
default_value=Undefined,
allow_none=False,
read_only=None,
help=None,
config=None,
**kwargs,
):
"""Declare a traitlet.
If *allow_none* is True, None is a valid value in addition to any
values that are normally valid. The default is up to the subclass.
For most trait types, the default value for ``allow_none`` is False.
If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
Extra metadata can be associated with the traitlet using the .tag() convenience method
or by using the traitlet instance's .metadata dictionary.
"""
if default_value is not Undefined:
self.default_value = default_value
if allow_none:
self.allow_none = allow_none
if read_only is not None:
self.read_only = read_only
self.help = help if help is not None else ""
if len(kwargs) > 0:
stacklevel = 1
f = inspect.currentframe()
# count supers to determine stacklevel for warning
assert f is not None
while f.f_code.co_name == "__init__":
stacklevel += 1
f = f.f_back
assert f is not None
mod = f.f_globals.get("__name__") or ""
pkg = mod.split(".", 1)[0]
key = tuple(["metadata-tag", pkg] + sorted(kwargs))
if _should_warn(key):
warn(
"metadata %s was set from the constructor. "
"With traitlets 4.1, metadata should be set using the .tag() method, "
"e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
DeprecationWarning,
stacklevel=stacklevel,
)
if len(self.metadata) > 0:
self.metadata = self.metadata.copy()
self.metadata.update(kwargs)
else:
self.metadata = kwargs
else:
self.metadata = self.metadata.copy()
if config is not None:
self.metadata["config"] = config
# We add help to the metadata during a deprecation period so that
# code that looks for the help string there can find it.
if help is not None:
self.metadata["help"] = help
def from_string(self, s):
"""Get a value from a config string
such as an environment variable or CLI arguments.
Traits can override this method to define their own
parsing of config strings.
.. seealso:: item_from_string
.. versionadded:: 5.0
"""
if self.allow_none and s == "None":
return None
return s
def default(self, obj=None):
"""The default generator for this trait
Notes
-----
This method is registered to HasTraits classes during ``class_init``
in the same way that dynamic defaults defined by ``@default`` are.
"""
if self.default_value is not Undefined:
return self.default_value
elif hasattr(self, "make_dynamic_default"):
return self.make_dynamic_default() # type:ignore[attr-defined]
else:
# Undefined will raise in TraitType.get
return self.default_value
def get_default_value(self):
"""DEPRECATED: Retrieve the static default value for this trait.
Use self.default_value instead
"""
warn(
"get_default_value is deprecated in traitlets 4.0: use the .default_value attribute",
DeprecationWarning,
stacklevel=2,
)
return self.default_value
def init_default_value(self, obj):
"""DEPRECATED: Set the static default value for the trait type."""
warn(
"init_default_value is deprecated in traitlets 4.0, and may be removed in the future",
DeprecationWarning,
stacklevel=2,
)
value = self._validate(obj, self.default_value)
obj._trait_values[self.name] = value
return value
def get(self, obj, cls=None):
try:
value = obj._trait_values[self.name]
except KeyError:
# Check for a dynamic initializer.
default = obj.trait_defaults(self.name)
if default is Undefined:
warn(
"Explicit using of Undefined as the default value "
"is deprecated in traitlets 5.0, and may cause "
"exceptions in the future.",
DeprecationWarning,
stacklevel=2,
)
value = self._validate(obj, default)
obj._trait_values[self.name] = value
obj._notify_observers(
Bunch(
name=self.name,
value=value,
owner=obj,
type="default",
)
)
return value
except Exception:
# This should never be reached.
raise TraitError("Unexpected error in TraitType: default value not set properly")
else:
return value
def __get__(self, obj, cls=None):
"""Get the value of the trait by self.name for the instance.
Default values are instantiated when :meth:`HasTraits.__new__`
is called. Thus by the time this method gets called either the
default value or a user defined value (they called :meth:`__set__`)
is in the :class:`HasTraits` instance.
"""
if obj is None:
return self
else:
return self.get(obj, cls)
def set(self, obj, value):
new_value = self._validate(obj, value)
try:
old_value = obj._trait_values[self.name]
except KeyError:
old_value = self.default_value
obj._trait_values[self.name] = new_value
try:
silent = bool(old_value == new_value)
except Exception:
# if there is an error in comparing, default to notify
silent = False
if silent is not True:
# we explicitly compare silent to True just in case the equality
# comparison above returns something other than True/False
obj._notify_trait(self.name, old_value, new_value)
def __set__(self, obj, value):
"""Set the value of the trait by self.name for the instance.
Values pass through a validation stage where errors are raised when
impropper types, or types that cannot be coerced, are encountered.
"""
if self.read_only:
raise TraitError('The "%s" trait is read-only.' % self.name)
else:
self.set(obj, value)
def _validate(self, obj, value):
if value is None and self.allow_none:
return value
if hasattr(self, "validate"):
value = self.validate(obj, value) # type:ignore[attr-defined]
if obj._cross_validation_lock is False:
value = self._cross_validate(obj, value)
return value
def _cross_validate(self, obj, value):
if self.name in obj._trait_validators:
proposal = Bunch({"trait": self, "value": value, "owner": obj})
value = obj._trait_validators[self.name](obj, proposal)
elif hasattr(obj, "_%s_validate" % self.name):
meth_name = "_%s_validate" % self.name
cross_validate = getattr(obj, meth_name)
_deprecated_method(
cross_validate,
obj.__class__,
meth_name,
"use @validate decorator instead.",
)
value = cross_validate(value, self)
return value
def __or__(self, other):
if isinstance(other, Union):
return Union([self] + other.trait_types)
else:
return Union([self, other])
def info(self):
return self.info_text
def error(self, obj, value, error=None, info=None):
"""Raise a TraitError
Parameters
----------
obj : HasTraits or None
The instance which owns the trait. If not
object is given, then an object agnostic
error will be raised.
value : any
The value that caused the error.
error : Exception (default: None)
An error that was raised by a child trait.
The arguments of this exception should be
of the form ``(value, info, *traits)``.
Where the ``value`` and ``info`` are the
problem value, and string describing the
expected value. The ``traits`` are a series
of :class:`TraitType` instances that are
"children" of this one (the first being
the deepest).
info : str (default: None)
A description of the expected value. By
default this is infered from this trait's
``info`` method.
"""
if error is not None:
# handle nested error
error.args += (self,)
if self.name is not None:
# this is the root trait that must format the final message
chain = " of ".join(describe("a", t) for t in error.args[2:])
if obj is not None:
error.args = (
"The '%s' trait of %s instance contains %s which "
"expected %s, not %s."
% (
self.name,
describe("an", obj),
chain,
error.args[1],
describe("the", error.args[0]),
),
)
else:
error.args = (
"The '%s' trait contains %s which "
"expected %s, not %s."
% (
self.name,
chain,
error.args[1],
describe("the", error.args[0]),
),
)
raise error
else:
# this trait caused an error
if self.name is None:
# this is not the root trait
raise TraitError(value, info or self.info(), self)
else:
# this is the root trait
if obj is not None:
e = "The '{}' trait of {} instance expected {}, not {}.".format(
self.name,
class_of(obj),
self.info(),
describe("the", value),
)
else:
e = "The '{}' trait expected {}, not {}.".format(
self.name,
self.info(),
describe("the", value),
)
raise TraitError(e)
def get_metadata(self, key, default=None):
"""DEPRECATED: Get a metadata value.
Use .metadata[key] or .metadata.get(key, default) instead.
"""
if key == "help":
msg = "use the instance .help string directly, like x.help"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
return self.metadata.get(key, default)
def set_metadata(self, key, value):
"""DEPRECATED: Set a metadata key/value.
Use .metadata[key] = value instead.
"""
if key == "help":
msg = "use the instance .help string directly, like x.help = value"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
self.metadata[key] = value
def tag(self, **metadata):
"""Sets metadata and returns self.
This allows convenient metadata tagging when initializing the trait, such as:
Examples
--------
>>> Int(0).tag(config=True, sync=True)
<traitlets.traitlets.Int object at ...>
"""
maybe_constructor_keywords = set(metadata.keys()).intersection(
{"help", "allow_none", "read_only", "default_value"}
)
if maybe_constructor_keywords:
warn(
"The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s "
% maybe_constructor_keywords,
UserWarning,
stacklevel=2,
)
self.metadata.update(metadata)
return self
def default_value_repr(self):
return repr(self.default_value)
# -----------------------------------------------------------------------------
# The HasTraits implementation
# -----------------------------------------------------------------------------
class _CallbackWrapper:
"""An object adapting a on_trait_change callback into an observe callback.
The comparison operator __eq__ is implemented to enable removal of wrapped
callbacks.
"""
def __init__(self, cb):
self.cb = cb
# Bound methods have an additional 'self' argument.
offset = -1 if isinstance(self.cb, types.MethodType) else 0
self.nargs = len(getargspec(cb)[0]) + offset
if self.nargs > 4:
raise TraitError("a trait changed callback must have 0-4 arguments.")
def __eq__(self, other):
# The wrapper is equal to the wrapped element
if isinstance(other, _CallbackWrapper):
return self.cb == other.cb
else:
return self.cb == other
def __call__(self, change):
# The wrapper is callable
if self.nargs == 0:
self.cb()
elif self.nargs == 1:
self.cb(change.name)
elif self.nargs == 2:
self.cb(change.name, change.new)
elif self.nargs == 3:
self.cb(change.name, change.old, change.new)
elif self.nargs == 4:
self.cb(change.name, change.old, change.new, change.owner)
def _callback_wrapper(cb):
if isinstance(cb, _CallbackWrapper):
return cb
else:
return _CallbackWrapper(cb)
class MetaHasDescriptors(type):
"""A metaclass for HasDescriptors.
This metaclass makes sure that any TraitType class attributes are
instantiated and sets their name attribute.
"""
def __new__(mcls, name, bases, classdict):
"""Create the HasDescriptors class."""
for k, v in classdict.items():
# ----------------------------------------------------------------
# Support of deprecated behavior allowing for TraitType types
# to be used instead of TraitType instances.
if inspect.isclass(v) and issubclass(v, TraitType):
warn(
"Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
" Passing types is deprecated in traitlets 4.1.",
DeprecationWarning,
stacklevel=2,
)
classdict[k] = v()
# ----------------------------------------------------------------
return super().__new__(mcls, name, bases, classdict)
def __init__(cls, name, bases, classdict):
"""Finish initializing the HasDescriptors class."""
super().__init__(name, bases, classdict)
cls.setup_class(classdict)
def setup_class(cls, classdict):
"""Setup descriptor instance on the class
This sets the :attr:`this_class` and :attr:`name` attributes of each
BaseDescriptor in the class dict of the newly created ``cls`` before
calling their :attr:`class_init` method.
"""
cls._descriptors = []
for k, v in classdict.items():
if isinstance(v, BaseDescriptor):
v.class_init(cls, k)
for _, v in getmembers(cls):
if isinstance(v, BaseDescriptor):
v.subclass_init(cls)
cls._descriptors.append(v)
class MetaHasTraits(MetaHasDescriptors):
"""A metaclass for HasTraits."""
def setup_class(cls, classdict):
# for only the current class
cls._trait_default_generators = {}
# also looking at base classes
cls._all_trait_default_generators = {}
super().setup_class(classdict)
mro = cls.mro()
for name in dir(cls):
value = getattr(cls, name)
if isinstance(value, TraitType):
trait = value
default_method_name = "_%s_default" % name
try:
mro_trait = mro[: mro.index(trait.this_class) + 1] # type:ignore[arg-type]
except ValueError:
# this_class not in mro
pass
for c in mro_trait: