Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/traitlets/traitlets.py: 13%
1579 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
1"""
2A lightweight Traits like module.
4This is designed to provide a lightweight, simple, pure Python version of
5many of the capabilities of enthought.traits. This includes:
7* Validation
8* Type specification with defaults
9* Static and dynamic notification
10* Basic predefined types
11* An API that is similar to enthought.traits
13We don't support:
15* Delegation
16* Automatic GUI generation
17* A full set of trait types. Most importantly, we don't provide container
18 traits (list, dict, tuple) that can trigger notifications if their
19 contents change.
20* API compatibility with enthought.traits
22There are also some important difference in our design:
24* enthought.traits does not validate default values. We do.
26We choose to create this module because we need these capabilities, but
27we need them to be pure Python so they work in all Python implementations,
28including Jython and IronPython.
30Inheritance diagram:
32.. inheritance-diagram:: traitlets.traitlets
33 :parts: 3
34"""
36# Copyright (c) IPython Development Team.
37# Distributed under the terms of the Modified BSD License.
38#
39# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
40# also under the terms of the Modified BSD License.
42import contextlib
43import enum
44import inspect
45import os
46import re
47import sys
48import types
49import typing as t
50from ast import literal_eval
51from warnings import warn, warn_explicit
53from .utils.bunch import Bunch
54from .utils.descriptions import add_article, class_of, describe, repr_type
55from .utils.getargspec import getargspec
56from .utils.importstring import import_item
57from .utils.sentinel import Sentinel
59SequenceTypes = (list, tuple, set, frozenset)
61# backward compatibility, use to differ between Python 2 and 3.
62ClassTypes = (type,)
64# exports:
66__all__ = [
67 "All",
68 "Any",
69 "BaseDescriptor",
70 "Bool",
71 "Bytes",
72 "CBool",
73 "CBytes",
74 "CComplex",
75 "CFloat",
76 "CInt",
77 "CLong",
78 "CRegExp",
79 "CUnicode",
80 "Callable",
81 "CaselessStrEnum",
82 "ClassBasedTraitType",
83 "Complex",
84 "Container",
85 "DefaultHandler",
86 "Dict",
87 "DottedObjectName",
88 "Enum",
89 "EventHandler",
90 "Float",
91 "ForwardDeclaredInstance",
92 "ForwardDeclaredMixin",
93 "ForwardDeclaredType",
94 "FuzzyEnum",
95 "HasDescriptors",
96 "HasTraits",
97 "Instance",
98 "Int",
99 "Integer",
100 "List",
101 "Long",
102 "MetaHasDescriptors",
103 "MetaHasTraits",
104 "ObjectName",
105 "ObserveHandler",
106 "Set",
107 "TCPAddress",
108 "This",
109 "TraitError",
110 "TraitType",
111 "Tuple",
112 "Type",
113 "Unicode",
114 "Undefined",
115 "Union",
116 "UseEnum",
117 "ValidateHandler",
118 "default",
119 "directional_link",
120 "dlink",
121 "link",
122 "observe",
123 "observe_compat",
124 "parse_notifier_name",
125 "validate",
126]
128# any TraitType subclass (that doesn't start with _) will be added automatically
130# -----------------------------------------------------------------------------
131# Basic classes
132# -----------------------------------------------------------------------------
135Undefined = Sentinel(
136 "Undefined",
137 "traitlets",
138 """
139Used in Traitlets to specify that no defaults are set in kwargs
140""",
141)
143All = Sentinel(
144 "All",
145 "traitlets",
146 """
147Used in Traitlets to listen to all types of notification or to notifications
148from all trait attributes.
149""",
150)
152# Deprecated alias
153NoDefaultSpecified = Undefined
156class TraitError(Exception):
157 pass
160# -----------------------------------------------------------------------------
161# Utilities
162# -----------------------------------------------------------------------------
164_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
167def isidentifier(s):
168 return s.isidentifier()
171_deprecations_shown = set()
174def _should_warn(key):
175 """Add our own checks for too many deprecation warnings.
177 Limit to once per package.
178 """
179 env_flag = os.environ.get("TRAITLETS_ALL_DEPRECATIONS")
180 if env_flag and env_flag != "0":
181 return True
183 if key not in _deprecations_shown:
184 _deprecations_shown.add(key)
185 return True
186 else:
187 return False
190def _deprecated_method(method, cls, method_name, msg):
191 """Show deprecation warning about a magic method definition.
193 Uses warn_explicit to bind warning to method definition instead of triggering code,
194 which isn't relevant.
195 """
196 warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
197 classname=cls.__name__, method_name=method_name, msg=msg
198 )
200 for parent in inspect.getmro(cls):
201 if method_name in parent.__dict__:
202 cls = parent
203 break
204 # limit deprecation messages to once per package
205 package_name = cls.__module__.split(".", 1)[0]
206 key = (package_name, msg)
207 if not _should_warn(key):
208 return
209 try:
210 fname = inspect.getsourcefile(method) or "<unknown>"
211 lineno = inspect.getsourcelines(method)[1] or 0
212 except (OSError, TypeError) as e:
213 # Failed to inspect for some reason
214 warn(warn_msg + ("\n(inspection failed) %s" % e), DeprecationWarning)
215 else:
216 warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
219def _safe_literal_eval(s):
220 """Safely evaluate an expression
222 Returns original string if eval fails.
224 Use only where types are ambiguous.
225 """
226 try:
227 return literal_eval(s)
228 except (NameError, SyntaxError, ValueError):
229 return s
232def is_trait(t):
233 """Returns whether the given value is an instance or subclass of TraitType."""
234 return isinstance(t, TraitType) or (isinstance(t, type) and issubclass(t, TraitType))
237def parse_notifier_name(names):
238 """Convert the name argument to a list of names.
240 Examples
241 --------
242 >>> parse_notifier_name([])
243 [traitlets.All]
244 >>> parse_notifier_name("a")
245 ['a']
246 >>> parse_notifier_name(["a", "b"])
247 ['a', 'b']
248 >>> parse_notifier_name(All)
249 [traitlets.All]
250 """
251 if names is All or isinstance(names, str):
252 return [names]
253 else:
254 if not names or All in names:
255 return [All]
256 for n in names:
257 if not isinstance(n, str):
258 raise TypeError("names must be strings, not %r" % n)
259 return names
262class _SimpleTest:
263 def __init__(self, value):
264 self.value = value
266 def __call__(self, test):
267 return test == self.value
269 def __repr__(self):
270 return "<SimpleTest(%r)" % self.value
272 def __str__(self):
273 return self.__repr__()
276def getmembers(object, predicate=None):
277 """A safe version of inspect.getmembers that handles missing attributes.
279 This is useful when there are descriptor based attributes that for
280 some reason raise AttributeError even though they exist. This happens
281 in zope.inteface with the __provides__ attribute.
282 """
283 results = []
284 for key in dir(object):
285 try:
286 value = getattr(object, key)
287 except AttributeError:
288 pass
289 else:
290 if not predicate or predicate(value):
291 results.append((key, value))
292 results.sort()
293 return results
296def _validate_link(*tuples):
297 """Validate arguments for traitlet link functions"""
298 for tup in tuples:
299 if not len(tup) == 2:
300 raise TypeError(
301 "Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t
302 )
303 obj, trait_name = tup
304 if not isinstance(obj, HasTraits):
305 raise TypeError("Each object must be HasTraits, not %r" % type(obj))
306 if trait_name not in obj.traits():
307 raise TypeError(f"{obj!r} has no trait {trait_name!r}")
310class link:
311 """Link traits from different objects together so they remain in sync.
313 Parameters
314 ----------
315 source : (object / attribute name) pair
316 target : (object / attribute name) pair
317 transform: iterable with two callables (optional)
318 Data transformation between source and target and target and source.
320 Examples
321 --------
322 >>> class X(HasTraits):
323 ... value = Int()
325 >>> src = X(value=1)
326 >>> tgt = X(value=42)
327 >>> c = link((src, "value"), (tgt, "value"))
329 Setting source updates target objects:
330 >>> src.value = 5
331 >>> tgt.value
332 5
333 """
335 updating = False
337 def __init__(self, source, target, transform=None):
338 _validate_link(source, target)
339 self.source, self.target = source, target
340 self._transform, self._transform_inv = transform if transform else (lambda x: x,) * 2
342 self.link()
344 def link(self):
345 try:
346 setattr(
347 self.target[0],
348 self.target[1],
349 self._transform(getattr(self.source[0], self.source[1])),
350 )
352 finally:
353 self.source[0].observe(self._update_target, names=self.source[1])
354 self.target[0].observe(self._update_source, names=self.target[1])
356 @contextlib.contextmanager
357 def _busy_updating(self):
358 self.updating = True
359 try:
360 yield
361 finally:
362 self.updating = False
364 def _update_target(self, change):
365 if self.updating:
366 return
367 with self._busy_updating():
368 setattr(self.target[0], self.target[1], self._transform(change.new))
369 if getattr(self.source[0], self.source[1]) != change.new:
370 raise TraitError(
371 "Broken link {}: the source value changed while updating "
372 "the target.".format(self)
373 )
375 def _update_source(self, change):
376 if self.updating:
377 return
378 with self._busy_updating():
379 setattr(self.source[0], self.source[1], self._transform_inv(change.new))
380 if getattr(self.target[0], self.target[1]) != change.new:
381 raise TraitError(
382 "Broken link {}: the target value changed while updating "
383 "the source.".format(self)
384 )
386 def unlink(self):
387 self.source[0].unobserve(self._update_target, names=self.source[1])
388 self.target[0].unobserve(self._update_source, names=self.target[1])
391class directional_link:
392 """Link the trait of a source object with traits of target objects.
394 Parameters
395 ----------
396 source : (object, attribute name) pair
397 target : (object, attribute name) pair
398 transform: callable (optional)
399 Data transformation between source and target.
401 Examples
402 --------
403 >>> class X(HasTraits):
404 ... value = Int()
406 >>> src = X(value=1)
407 >>> tgt = X(value=42)
408 >>> c = directional_link((src, "value"), (tgt, "value"))
410 Setting source updates target objects:
411 >>> src.value = 5
412 >>> tgt.value
413 5
415 Setting target does not update source object:
416 >>> tgt.value = 6
417 >>> src.value
418 5
420 """
422 updating = False
424 def __init__(self, source, target, transform=None):
425 self._transform = transform if transform else lambda x: x
426 _validate_link(source, target)
427 self.source, self.target = source, target
428 self.link()
430 def link(self):
431 try:
432 setattr(
433 self.target[0],
434 self.target[1],
435 self._transform(getattr(self.source[0], self.source[1])),
436 )
437 finally:
438 self.source[0].observe(self._update, names=self.source[1])
440 @contextlib.contextmanager
441 def _busy_updating(self):
442 self.updating = True
443 try:
444 yield
445 finally:
446 self.updating = False
448 def _update(self, change):
449 if self.updating:
450 return
451 with self._busy_updating():
452 setattr(self.target[0], self.target[1], self._transform(change.new))
454 def unlink(self):
455 self.source[0].unobserve(self._update, names=self.source[1])
458dlink = directional_link
461# -----------------------------------------------------------------------------
462# Base Descriptor Class
463# -----------------------------------------------------------------------------
466class BaseDescriptor:
467 """Base descriptor class
469 Notes
470 -----
471 This implements Python's descriptor protocol.
473 This class is the base class for all such descriptors. The
474 only magic we use is a custom metaclass for the main :class:`HasTraits`
475 class that does the following:
477 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
478 instance in the class dict to the name of the attribute.
479 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
480 instance in the class dict to the *class* that declared the trait.
481 This is used by the :class:`This` trait to allow subclasses to
482 accept superclasses for :class:`This` values.
483 """
485 name: t.Optional[str] = None
486 this_class: t.Optional[t.Type[t.Any]] = None
488 def class_init(self, cls, name):
489 """Part of the initialization which may depend on the underlying
490 HasDescriptors class.
492 It is typically overloaded for specific types.
494 This method is called by :meth:`MetaHasDescriptors.__init__`
495 passing the class (`cls`) and `name` under which the descriptor
496 has been assigned.
497 """
498 self.this_class = cls
499 self.name = name
501 def subclass_init(self, cls):
502 # Instead of HasDescriptors.setup_instance calling
503 # every instance_init, we opt in by default.
504 # This gives descriptors a change to opt out for
505 # performance reasons.
506 # Because most traits do not need instance_init,
507 # and it will otherwise be called for every HasTrait instance
508 # beging created, this otherwise gives a significant performance
509 # pentalty. Most TypeTraits in traitlets opt out.
510 cls._instance_inits.append(self.instance_init)
512 def instance_init(self, obj):
513 """Part of the initialization which may depend on the underlying
514 HasDescriptors instance.
516 It is typically overloaded for specific types.
518 This method is called by :meth:`HasTraits.__new__` and in the
519 :meth:`BaseDescriptor.instance_init` method of descriptors holding
520 other descriptors.
521 """
522 pass
525class TraitType(BaseDescriptor):
526 """A base class for all trait types."""
528 metadata: t.Dict[str, t.Any] = {}
529 allow_none = False
530 read_only = False
531 info_text = "any value"
532 default_value: t.Optional[t.Any] = Undefined
534 def __init__(
535 self,
536 default_value=Undefined,
537 allow_none=False,
538 read_only=None,
539 help=None,
540 config=None,
541 **kwargs,
542 ):
543 """Declare a traitlet.
545 If *allow_none* is True, None is a valid value in addition to any
546 values that are normally valid. The default is up to the subclass.
547 For most trait types, the default value for ``allow_none`` is False.
549 If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
551 Extra metadata can be associated with the traitlet using the .tag() convenience method
552 or by using the traitlet instance's .metadata dictionary.
553 """
554 if default_value is not Undefined:
555 self.default_value = default_value
556 if allow_none:
557 self.allow_none = allow_none
558 if read_only is not None:
559 self.read_only = read_only
560 self.help = help if help is not None else ""
561 if self.help:
562 # define __doc__ so that inspectors like autodoc find traits
563 self.__doc__ = self.help
565 if len(kwargs) > 0:
566 stacklevel = 1
567 f = inspect.currentframe()
568 # count supers to determine stacklevel for warning
569 assert f is not None
570 while f.f_code.co_name == "__init__":
571 stacklevel += 1
572 f = f.f_back
573 assert f is not None
574 mod = f.f_globals.get("__name__") or ""
575 pkg = mod.split(".", 1)[0]
576 key = tuple(["metadata-tag", pkg] + sorted(kwargs))
577 if _should_warn(key):
578 warn(
579 "metadata %s was set from the constructor. "
580 "With traitlets 4.1, metadata should be set using the .tag() method, "
581 "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
582 DeprecationWarning,
583 stacklevel=stacklevel,
584 )
585 if len(self.metadata) > 0:
586 self.metadata = self.metadata.copy()
587 self.metadata.update(kwargs)
588 else:
589 self.metadata = kwargs
590 else:
591 self.metadata = self.metadata.copy()
592 if config is not None:
593 self.metadata["config"] = config
595 # We add help to the metadata during a deprecation period so that
596 # code that looks for the help string there can find it.
597 if help is not None:
598 self.metadata["help"] = help
600 def from_string(self, s):
601 """Get a value from a config string
603 such as an environment variable or CLI arguments.
605 Traits can override this method to define their own
606 parsing of config strings.
608 .. seealso:: item_from_string
610 .. versionadded:: 5.0
611 """
612 if self.allow_none and s == "None":
613 return None
614 return s
616 def default(self, obj=None):
617 """The default generator for this trait
619 Notes
620 -----
621 This method is registered to HasTraits classes during ``class_init``
622 in the same way that dynamic defaults defined by ``@default`` are.
623 """
624 if self.default_value is not Undefined:
625 return self.default_value
626 elif hasattr(self, "make_dynamic_default"):
627 return self.make_dynamic_default()
628 else:
629 # Undefined will raise in TraitType.get
630 return self.default_value
632 def get_default_value(self):
633 """DEPRECATED: Retrieve the static default value for this trait.
634 Use self.default_value instead
635 """
636 warn(
637 "get_default_value is deprecated in traitlets 4.0: use the .default_value attribute",
638 DeprecationWarning,
639 stacklevel=2,
640 )
641 return self.default_value
643 def init_default_value(self, obj):
644 """DEPRECATED: Set the static default value for the trait type."""
645 warn(
646 "init_default_value is deprecated in traitlets 4.0, and may be removed in the future",
647 DeprecationWarning,
648 stacklevel=2,
649 )
650 value = self._validate(obj, self.default_value)
651 obj._trait_values[self.name] = value
652 return value
654 def get(self, obj, cls=None):
655 try:
656 value = obj._trait_values[self.name]
657 except KeyError:
658 # Check for a dynamic initializer.
659 default = obj.trait_defaults(self.name)
660 if default is Undefined:
661 warn(
662 "Explicit using of Undefined as the default value "
663 "is deprecated in traitlets 5.0, and may cause "
664 "exceptions in the future.",
665 DeprecationWarning,
666 stacklevel=2,
667 )
668 # Using a context manager has a large runtime overhead, so we
669 # write out the obj.cross_validation_lock call here.
670 _cross_validation_lock = obj._cross_validation_lock
671 try:
672 obj._cross_validation_lock = True
673 value = self._validate(obj, default)
674 finally:
675 obj._cross_validation_lock = _cross_validation_lock
676 obj._trait_values[self.name] = value
677 obj._notify_observers(
678 Bunch(
679 name=self.name,
680 value=value,
681 owner=obj,
682 type="default",
683 )
684 )
685 return value
686 except Exception as e:
687 # This should never be reached.
688 raise TraitError("Unexpected error in TraitType: default value not set properly") from e
689 else:
690 return value
692 def __get__(self, obj, cls=None):
693 """Get the value of the trait by self.name for the instance.
695 Default values are instantiated when :meth:`HasTraits.__new__`
696 is called. Thus by the time this method gets called either the
697 default value or a user defined value (they called :meth:`__set__`)
698 is in the :class:`HasTraits` instance.
699 """
700 if obj is None:
701 return self
702 else:
703 return self.get(obj, cls)
705 def set(self, obj, value):
706 new_value = self._validate(obj, value)
707 try:
708 old_value = obj._trait_values[self.name]
709 except KeyError:
710 old_value = self.default_value
712 obj._trait_values[self.name] = new_value
713 try:
714 silent = bool(old_value == new_value)
715 except Exception:
716 # if there is an error in comparing, default to notify
717 silent = False
718 if silent is not True:
719 # we explicitly compare silent to True just in case the equality
720 # comparison above returns something other than True/False
721 obj._notify_trait(self.name, old_value, new_value)
723 def __set__(self, obj, value):
724 """Set the value of the trait by self.name for the instance.
726 Values pass through a validation stage where errors are raised when
727 impropper types, or types that cannot be coerced, are encountered.
728 """
729 if self.read_only:
730 raise TraitError('The "%s" trait is read-only.' % self.name)
731 else:
732 self.set(obj, value)
734 def _validate(self, obj, value):
735 if value is None and self.allow_none:
736 return value
737 if hasattr(self, "validate"):
738 value = self.validate(obj, value)
739 if obj._cross_validation_lock is False:
740 value = self._cross_validate(obj, value)
741 return value
743 def _cross_validate(self, obj, value):
744 if self.name in obj._trait_validators:
745 proposal = Bunch({"trait": self, "value": value, "owner": obj})
746 value = obj._trait_validators[self.name](obj, proposal)
747 elif hasattr(obj, "_%s_validate" % self.name):
748 meth_name = "_%s_validate" % self.name
749 cross_validate = getattr(obj, meth_name)
750 _deprecated_method(
751 cross_validate,
752 obj.__class__,
753 meth_name,
754 "use @validate decorator instead.",
755 )
756 value = cross_validate(value, self)
757 return value
759 def __or__(self, other):
760 if isinstance(other, Union):
761 return Union([self] + other.trait_types)
762 else:
763 return Union([self, other])
765 def info(self):
766 return self.info_text
768 def error(self, obj, value, error=None, info=None):
769 """Raise a TraitError
771 Parameters
772 ----------
773 obj : HasTraits or None
774 The instance which owns the trait. If not
775 object is given, then an object agnostic
776 error will be raised.
777 value : any
778 The value that caused the error.
779 error : Exception (default: None)
780 An error that was raised by a child trait.
781 The arguments of this exception should be
782 of the form ``(value, info, *traits)``.
783 Where the ``value`` and ``info`` are the
784 problem value, and string describing the
785 expected value. The ``traits`` are a series
786 of :class:`TraitType` instances that are
787 "children" of this one (the first being
788 the deepest).
789 info : str (default: None)
790 A description of the expected value. By
791 default this is infered from this trait's
792 ``info`` method.
793 """
794 if error is not None:
795 # handle nested error
796 error.args += (self,)
797 if self.name is not None:
798 # this is the root trait that must format the final message
799 chain = " of ".join(describe("a", t) for t in error.args[2:])
800 if obj is not None:
801 error.args = (
802 "The '%s' trait of %s instance contains %s which "
803 "expected %s, not %s."
804 % (
805 self.name,
806 describe("an", obj),
807 chain,
808 error.args[1],
809 describe("the", error.args[0]),
810 ),
811 )
812 else:
813 error.args = (
814 "The '%s' trait contains %s which "
815 "expected %s, not %s."
816 % (
817 self.name,
818 chain,
819 error.args[1],
820 describe("the", error.args[0]),
821 ),
822 )
823 raise error
824 else:
825 # this trait caused an error
826 if self.name is None:
827 # this is not the root trait
828 raise TraitError(value, info or self.info(), self)
829 else:
830 # this is the root trait
831 if obj is not None:
832 e = "The '{}' trait of {} instance expected {}, not {}.".format(
833 self.name,
834 class_of(obj),
835 self.info(),
836 describe("the", value),
837 )
838 else:
839 e = "The '{}' trait expected {}, not {}.".format(
840 self.name,
841 self.info(),
842 describe("the", value),
843 )
844 raise TraitError(e)
846 def get_metadata(self, key, default=None):
847 """DEPRECATED: Get a metadata value.
849 Use .metadata[key] or .metadata.get(key, default) instead.
850 """
851 if key == "help":
852 msg = "use the instance .help string directly, like x.help"
853 else:
854 msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
855 warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
856 return self.metadata.get(key, default)
858 def set_metadata(self, key, value):
859 """DEPRECATED: Set a metadata key/value.
861 Use .metadata[key] = value instead.
862 """
863 if key == "help":
864 msg = "use the instance .help string directly, like x.help = value"
865 else:
866 msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
867 warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
868 self.metadata[key] = value
870 def tag(self, **metadata):
871 """Sets metadata and returns self.
873 This allows convenient metadata tagging when initializing the trait, such as:
875 Examples
876 --------
877 >>> Int(0).tag(config=True, sync=True)
878 <traitlets.traitlets.Int object at ...>
880 """
881 maybe_constructor_keywords = set(metadata.keys()).intersection(
882 {"help", "allow_none", "read_only", "default_value"}
883 )
884 if maybe_constructor_keywords:
885 warn(
886 "The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s "
887 % maybe_constructor_keywords,
888 UserWarning,
889 stacklevel=2,
890 )
892 self.metadata.update(metadata)
893 return self
895 def default_value_repr(self):
896 return repr(self.default_value)
899# -----------------------------------------------------------------------------
900# The HasTraits implementation
901# -----------------------------------------------------------------------------
904class _CallbackWrapper:
905 """An object adapting a on_trait_change callback into an observe callback.
907 The comparison operator __eq__ is implemented to enable removal of wrapped
908 callbacks.
909 """
911 def __init__(self, cb):
912 self.cb = cb
913 # Bound methods have an additional 'self' argument.
914 offset = -1 if isinstance(self.cb, types.MethodType) else 0
915 self.nargs = len(getargspec(cb)[0]) + offset
916 if self.nargs > 4:
917 raise TraitError("a trait changed callback must have 0-4 arguments.")
919 def __eq__(self, other):
920 # The wrapper is equal to the wrapped element
921 if isinstance(other, _CallbackWrapper):
922 return self.cb == other.cb
923 else:
924 return self.cb == other
926 def __call__(self, change):
927 # The wrapper is callable
928 if self.nargs == 0:
929 self.cb()
930 elif self.nargs == 1:
931 self.cb(change.name)
932 elif self.nargs == 2:
933 self.cb(change.name, change.new)
934 elif self.nargs == 3:
935 self.cb(change.name, change.old, change.new)
936 elif self.nargs == 4:
937 self.cb(change.name, change.old, change.new, change.owner)
940def _callback_wrapper(cb):
941 if isinstance(cb, _CallbackWrapper):
942 return cb
943 else:
944 return _CallbackWrapper(cb)
947class MetaHasDescriptors(type):
948 """A metaclass for HasDescriptors.
950 This metaclass makes sure that any TraitType class attributes are
951 instantiated and sets their name attribute.
952 """
954 def __new__(mcls, name, bases, classdict): # noqa
955 """Create the HasDescriptors class."""
956 for k, v in classdict.items():
957 # ----------------------------------------------------------------
958 # Support of deprecated behavior allowing for TraitType types
959 # to be used instead of TraitType instances.
960 if inspect.isclass(v) and issubclass(v, TraitType):
961 warn(
962 "Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
963 " Passing types is deprecated in traitlets 4.1.",
964 DeprecationWarning,
965 stacklevel=2,
966 )
967 classdict[k] = v()
968 # ----------------------------------------------------------------
970 return super().__new__(mcls, name, bases, classdict)
972 def __init__(cls, name, bases, classdict):
973 """Finish initializing the HasDescriptors class."""
974 super().__init__(name, bases, classdict)
975 cls.setup_class(classdict)
977 def setup_class(cls, classdict):
978 """Setup descriptor instance on the class
980 This sets the :attr:`this_class` and :attr:`name` attributes of each
981 BaseDescriptor in the class dict of the newly created ``cls`` before
982 calling their :attr:`class_init` method.
983 """
984 cls._descriptors = []
985 cls._instance_inits = []
986 for k, v in classdict.items():
987 if isinstance(v, BaseDescriptor):
988 v.class_init(cls, k)
990 for _, v in getmembers(cls):
991 if isinstance(v, BaseDescriptor):
992 v.subclass_init(cls)
993 cls._descriptors.append(v)
996class MetaHasTraits(MetaHasDescriptors):
997 """A metaclass for HasTraits."""
999 def setup_class(cls, classdict): # noqa
1000 # for only the current class
1001 cls._trait_default_generators = {}
1002 # also looking at base classes
1003 cls._all_trait_default_generators = {}
1004 cls._traits = {}
1005 cls._static_immutable_initial_values = {}
1007 super().setup_class(classdict)
1009 mro = cls.mro()
1011 for name in dir(cls):
1012 # Some descriptors raise AttributeError like zope.interface's
1013 # __provides__ attributes even though they exist. This causes
1014 # AttributeErrors even though they are listed in dir(cls).
1015 try:
1016 value = getattr(cls, name)
1017 except AttributeError:
1018 continue
1019 if isinstance(value, TraitType):
1020 cls._traits[name] = value
1021 trait = value
1022 default_method_name = "_%s_default" % name
1023 mro_trait = mro
1024 try:
1025 mro_trait = mro[: mro.index(trait.this_class) + 1] # type:ignore[arg-type]
1026 except ValueError:
1027 # this_class not in mro
1028 pass
1029 for c in mro_trait:
1030 if default_method_name in c.__dict__:
1031 cls._all_trait_default_generators[name] = c.__dict__[default_method_name]
1032 break
1033 if name in c.__dict__.get("_trait_default_generators", {}):
1034 cls._all_trait_default_generators[name] = c._trait_default_generators[name] # type: ignore[attr-defined]
1035 break
1036 else:
1037 # We don't have a dynamic default generator using @default etc.
1038 # Now if the default value is not dynamic and immutable (string, number)
1039 # and does not require any validation, we keep them in a dict
1040 # of initial values to speed up instance creation.
1041 # This is a very specific optimization, but a very common scenario in
1042 # for instance ipywidgets.
1043 none_ok = trait.default_value is None and trait.allow_none
1044 if (
1045 type(trait) in [CInt, Int]
1046 and trait.min is None # type: ignore[attr-defined]
1047 and trait.max is None # type: ignore[attr-defined]
1048 and (isinstance(trait.default_value, int) or none_ok)
1049 ):
1050 cls._static_immutable_initial_values[name] = trait.default_value
1051 elif (
1052 type(trait) in [CFloat, Float]
1053 and trait.min is None # type: ignore[attr-defined]
1054 and trait.max is None # type: ignore[attr-defined]
1055 and (isinstance(trait.default_value, float) or none_ok)
1056 ):
1057 cls._static_immutable_initial_values[name] = trait.default_value
1058 elif type(trait) in [CBool, Bool] and (
1059 isinstance(trait.default_value, bool) or none_ok
1060 ):
1061 cls._static_immutable_initial_values[name] = trait.default_value
1062 elif type(trait) in [CUnicode, Unicode] and (
1063 isinstance(trait.default_value, str) or none_ok
1064 ):
1065 cls._static_immutable_initial_values[name] = trait.default_value
1066 elif type(trait) == Any and (
1067 isinstance(trait.default_value, (str, int, float, bool)) or none_ok
1068 ):
1069 cls._static_immutable_initial_values[name] = trait.default_value
1070 elif type(trait) == Union and trait.default_value is None:
1071 cls._static_immutable_initial_values[name] = None
1072 elif (
1073 isinstance(trait, Instance)
1074 and trait.default_args is None
1075 and trait.default_kwargs is None
1076 and trait.allow_none
1077 ):
1078 cls._static_immutable_initial_values[name] = None
1080 # we always add it, because a class may change when we call add_trait
1081 # and then the instance may not have all the _static_immutable_initial_values
1082 cls._all_trait_default_generators[name] = trait.default
1085def observe(*names: t.Union[Sentinel, str], type: str = "change") -> "ObserveHandler":
1086 """A decorator which can be used to observe Traits on a class.
1088 The handler passed to the decorator will be called with one ``change``
1089 dict argument. The change dictionary at least holds a 'type' key and a
1090 'name' key, corresponding respectively to the type of notification and the
1091 name of the attribute that triggered the notification.
1093 Other keys may be passed depending on the value of 'type'. In the case
1094 where type is 'change', we also have the following keys:
1095 * ``owner`` : the HasTraits instance
1096 * ``old`` : the old value of the modified trait attribute
1097 * ``new`` : the new value of the modified trait attribute
1098 * ``name`` : the name of the modified trait attribute.
1100 Parameters
1101 ----------
1102 *names
1103 The str names of the Traits to observe on the object.
1104 type : str, kwarg-only
1105 The type of event to observe (e.g. 'change')
1106 """
1107 if not names:
1108 raise TypeError("Please specify at least one trait name to observe.")
1109 for name in names:
1110 if name is not All and not isinstance(name, str):
1111 raise TypeError("trait names to observe must be strings or All, not %r" % name)
1112 return ObserveHandler(names, type=type)
1115def observe_compat(func):
1116 """Backward-compatibility shim decorator for observers
1118 Use with:
1120 @observe('name')
1121 @observe_compat
1122 def _foo_changed(self, change):
1123 ...
1125 With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
1126 Allows adoption of new observer API without breaking subclasses that override and super.
1127 """
1129 def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
1130 if isinstance(change_or_name, dict):
1131 change = change_or_name
1132 else:
1133 clsname = self.__class__.__name__
1134 warn(
1135 "A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API"
1136 % (clsname, change_or_name),
1137 DeprecationWarning,
1138 )
1139 change = Bunch(
1140 type="change",
1141 old=old,
1142 new=new,
1143 name=change_or_name,
1144 owner=self,
1145 )
1146 return func(self, change)
1148 return compatible_observer
1151def validate(*names: t.Union[Sentinel, str]) -> "ValidateHandler":
1152 """A decorator to register cross validator of HasTraits object's state
1153 when a Trait is set.
1155 The handler passed to the decorator must have one ``proposal`` dict argument.
1156 The proposal dictionary must hold the following keys:
1158 * ``owner`` : the HasTraits instance
1159 * ``value`` : the proposed value for the modified trait attribute
1160 * ``trait`` : the TraitType instance associated with the attribute
1162 Parameters
1163 ----------
1164 *names
1165 The str names of the Traits to validate.
1167 Notes
1168 -----
1169 Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
1170 the registered cross validator could potentially make changes to attributes
1171 of the ``HasTraits`` instance. However, we recommend not to do so. The reason
1172 is that the cross-validation of attributes may run in arbitrary order when
1173 exiting the ``hold_trait_notifications`` context, and such changes may not
1174 commute.
1175 """
1176 if not names:
1177 raise TypeError("Please specify at least one trait name to validate.")
1178 for name in names:
1179 if name is not All and not isinstance(name, str):
1180 raise TypeError("trait names to validate must be strings or All, not %r" % name)
1181 return ValidateHandler(names)
1184def default(name: str) -> "DefaultHandler":
1185 """A decorator which assigns a dynamic default for a Trait on a HasTraits object.
1187 Parameters
1188 ----------
1189 name
1190 The str name of the Trait on the object whose default should be generated.
1192 Notes
1193 -----
1194 Unlike observers and validators which are properties of the HasTraits
1195 instance, default value generators are class-level properties.
1197 Besides, default generators are only invoked if they are registered in
1198 subclasses of `this_type`.
1200 ::
1202 class A(HasTraits):
1203 bar = Int()
1205 @default('bar')
1206 def get_bar_default(self):
1207 return 11
1209 class B(A):
1210 bar = Float() # This trait ignores the default generator defined in
1211 # the base class A
1213 class C(B):
1215 @default('bar')
1216 def some_other_default(self): # This default generator should not be
1217 return 3.0 # ignored since it is defined in a
1218 # class derived from B.a.this_class.
1219 """
1220 if not isinstance(name, str):
1221 raise TypeError("Trait name must be a string or All, not %r" % name)
1222 return DefaultHandler(name)
1225class EventHandler(BaseDescriptor):
1226 def _init_call(self, func):
1227 self.func = func
1228 return self
1230 def __call__(self, *args, **kwargs):
1231 """Pass `*args` and `**kwargs` to the handler's function if it exists."""
1232 if hasattr(self, "func"):
1233 return self.func(*args, **kwargs)
1234 else:
1235 return self._init_call(*args, **kwargs)
1237 def __get__(self, inst, cls=None):
1238 if inst is None:
1239 return self
1240 return types.MethodType(self.func, inst)
1243class ObserveHandler(EventHandler):
1244 def __init__(self, names, type):
1245 self.trait_names = names
1246 self.type = type
1248 def instance_init(self, inst):
1249 inst.observe(self, self.trait_names, type=self.type)
1252class ValidateHandler(EventHandler):
1253 def __init__(self, names):
1254 self.trait_names = names
1256 def instance_init(self, inst):
1257 inst._register_validator(self, self.trait_names)
1260class DefaultHandler(EventHandler):
1261 def __init__(self, name):
1262 self.trait_name = name
1264 def class_init(self, cls, name):
1265 super().class_init(cls, name)
1266 cls._trait_default_generators[self.trait_name] = self
1269class HasDescriptors(metaclass=MetaHasDescriptors):
1270 """The base class for all classes that have descriptors."""
1272 def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any:
1273 # Pass cls as args[0] to allow "cls" as keyword argument
1274 cls = args[0]
1275 args = args[1:]
1277 # This is needed because object.__new__ only accepts
1278 # the cls argument.
1279 new_meth = super(HasDescriptors, cls).__new__
1280 if new_meth is object.__new__:
1281 inst = new_meth(cls)
1282 else:
1283 inst = new_meth(cls, *args, **kwargs)
1284 inst.setup_instance(*args, **kwargs)
1285 return inst
1287 def setup_instance(*args, **kwargs):
1288 """
1289 This is called **before** self.__init__ is called.
1290 """
1291 # Pass self as args[0] to allow "self" as keyword argument
1292 self = args[0]
1293 args = args[1:]
1295 self._cross_validation_lock = False # type:ignore[attr-defined]
1296 cls = self.__class__
1297 # Let descriptors performance initialization when a HasDescriptor
1298 # instance is created. This allows registration of observers and
1299 # default creations or other bookkeepings.
1300 # Note that descriptors can opt-out of this behavior by overriding
1301 # subclass_init.
1302 for init in cls._instance_inits:
1303 init(self)
1306class HasTraits(HasDescriptors, metaclass=MetaHasTraits):
1307 _trait_values: t.Dict[str, t.Any]
1308 _static_immutable_initial_values: t.Dict[str, t.Any]
1309 _trait_notifiers: t.Dict[str, t.Any]
1310 _trait_validators: t.Dict[str, t.Any]
1311 _cross_validation_lock: bool
1312 _traits: t.Dict[str, t.Any]
1313 _all_trait_default_generators: t.Dict[str, t.Any]
1315 def setup_instance(*args, **kwargs):
1316 # Pass self as args[0] to allow "self" as keyword argument
1317 self = args[0]
1318 args = args[1:]
1320 # although we'd prefer to set only the initial values not present
1321 # in kwargs, we will overwrite them in `__init__`, and simply making
1322 # a copy of a dict is faster than checking for each key.
1323 self._trait_values = self._static_immutable_initial_values.copy()
1324 self._trait_notifiers = {}
1325 self._trait_validators = {}
1326 self._cross_validation_lock = False
1327 super(HasTraits, self).setup_instance(*args, **kwargs)
1329 def __init__(self, *args, **kwargs):
1330 # Allow trait values to be set using keyword arguments.
1331 # We need to use setattr for this to trigger validation and
1332 # notifications.
1333 super_args = args
1334 super_kwargs = {}
1336 if kwargs:
1337 # this is a simplified (and faster) version of
1338 # the hold_trait_notifications(self) context manager
1339 def ignore(*_ignore_args):
1340 pass
1342 self.notify_change = ignore # type:ignore[assignment]
1343 self._cross_validation_lock = True
1344 changes = {}
1345 for key, value in kwargs.items():
1346 if self.has_trait(key):
1347 setattr(self, key, value)
1348 changes[key] = Bunch(
1349 name=key,
1350 old=None,
1351 new=value,
1352 owner=self,
1353 type="change",
1354 )
1355 else:
1356 # passthrough args that don't set traits to super
1357 super_kwargs[key] = value
1358 # notify and cross validate all trait changes that were set in kwargs
1359 changed = set(kwargs) & set(self._traits)
1360 for key in changed:
1361 value = self._traits[key]._cross_validate(self, getattr(self, key))
1362 self.set_trait(key, value)
1363 changes[key]['new'] = value
1364 self._cross_validation_lock = False
1365 # Restore method retrieval from class
1366 del self.notify_change
1367 for key in changed:
1368 self.notify_change(changes[key])
1370 try:
1371 super().__init__(*super_args, **super_kwargs)
1372 except TypeError as e:
1373 arg_s_list = [repr(arg) for arg in super_args]
1374 for k, v in super_kwargs.items():
1375 arg_s_list.append(f"{k}={v!r}")
1376 arg_s = ", ".join(arg_s_list)
1377 warn(
1378 "Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n"
1379 "{error}\n"
1380 "This is deprecated in traitlets 4.2."
1381 "This error will be raised in a future release of traitlets.".format(
1382 arg_s=arg_s,
1383 classname=self.__class__.__name__,
1384 error=e,
1385 ),
1386 DeprecationWarning,
1387 stacklevel=2,
1388 )
1390 def __getstate__(self):
1391 d = self.__dict__.copy()
1392 # event handlers stored on an instance are
1393 # expected to be reinstantiated during a
1394 # recall of instance_init during __setstate__
1395 d["_trait_notifiers"] = {}
1396 d["_trait_validators"] = {}
1397 d["_trait_values"] = self._trait_values.copy()
1398 d["_cross_validation_lock"] = False # FIXME: raise if cloning locked!
1400 return d
1402 def __setstate__(self, state):
1403 self.__dict__ = state.copy()
1405 # event handlers are reassigned to self
1406 cls = self.__class__
1407 for key in dir(cls):
1408 # Some descriptors raise AttributeError like zope.interface's
1409 # __provides__ attributes even though they exist. This causes
1410 # AttributeErrors even though they are listed in dir(cls).
1411 try:
1412 value = getattr(cls, key)
1413 except AttributeError:
1414 pass
1415 else:
1416 if isinstance(value, EventHandler):
1417 value.instance_init(self)
1419 @property
1420 @contextlib.contextmanager
1421 def cross_validation_lock(self):
1422 """
1423 A contextmanager for running a block with our cross validation lock set
1424 to True.
1426 At the end of the block, the lock's value is restored to its value
1427 prior to entering the block.
1428 """
1429 if self._cross_validation_lock:
1430 yield
1431 return
1432 else:
1433 try:
1434 self._cross_validation_lock = True
1435 yield
1436 finally:
1437 self._cross_validation_lock = False
1439 @contextlib.contextmanager
1440 def hold_trait_notifications(self):
1441 """Context manager for bundling trait change notifications and cross
1442 validation.
1444 Use this when doing multiple trait assignments (init, config), to avoid
1445 race conditions in trait notifiers requesting other trait values.
1446 All trait notifications will fire after all values have been assigned.
1447 """
1448 if self._cross_validation_lock:
1449 yield
1450 return
1451 else:
1452 cache: t.Dict[str, t.Any] = {}
1454 def compress(past_changes, change):
1455 """Merges the provided change with the last if possible."""
1456 if past_changes is None:
1457 return [change]
1458 else:
1459 if past_changes[-1]["type"] == "change" and change.type == "change":
1460 past_changes[-1]["new"] = change.new
1461 else:
1462 # In case of changes other than 'change', append the notification.
1463 past_changes.append(change)
1464 return past_changes
1466 def hold(change):
1467 name = change.name
1468 cache[name] = compress(cache.get(name), change)
1470 try:
1471 # Replace notify_change with `hold`, caching and compressing
1472 # notifications, disable cross validation and yield.
1473 self.notify_change = hold # type:ignore[assignment]
1474 self._cross_validation_lock = True
1475 yield
1476 # Cross validate final values when context is released.
1477 for name in list(cache.keys()):
1478 trait = getattr(self.__class__, name)
1479 value = trait._cross_validate(self, getattr(self, name))
1480 self.set_trait(name, value)
1481 except TraitError as e:
1482 # Roll back in case of TraitError during final cross validation.
1483 self.notify_change = lambda x: None # type:ignore[assignment]
1484 for name, changes in cache.items():
1485 for change in changes[::-1]:
1486 # TODO: Separate in a rollback function per notification type.
1487 if change.type == "change":
1488 if change.old is not Undefined:
1489 self.set_trait(name, change.old)
1490 else:
1491 self._trait_values.pop(name)
1492 cache = {}
1493 raise e
1494 finally:
1495 self._cross_validation_lock = False
1496 # Restore method retrieval from class
1497 del self.notify_change
1499 # trigger delayed notifications
1500 for changes in cache.values():
1501 for change in changes:
1502 self.notify_change(change)
1504 def _notify_trait(self, name, old_value, new_value):
1505 self.notify_change(
1506 Bunch(
1507 name=name,
1508 old=old_value,
1509 new=new_value,
1510 owner=self,
1511 type="change",
1512 )
1513 )
1515 def notify_change(self, change):
1516 """Notify observers of a change event"""
1517 return self._notify_observers(change)
1519 def _notify_observers(self, event):
1520 """Notify observers of any event"""
1521 if not isinstance(event, Bunch):
1522 # cast to bunch if given a dict
1523 event = Bunch(event)
1524 name, type = event['name'], event['type']
1526 callables = []
1527 if name in self._trait_notifiers:
1528 callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
1529 callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
1530 if All in self._trait_notifiers: # type:ignore[comparison-overlap]
1531 callables.extend(
1532 self._trait_notifiers.get(All, {}).get(type, []) # type:ignore[call-overload]
1533 )
1534 callables.extend(
1535 self._trait_notifiers.get(All, {}).get(All, []) # type:ignore[call-overload]
1536 )
1538 # Now static ones
1539 magic_name = "_%s_changed" % name
1540 if event['type'] == "change" and hasattr(self, magic_name):
1541 class_value = getattr(self.__class__, magic_name)
1542 if not isinstance(class_value, ObserveHandler):
1543 _deprecated_method(
1544 class_value,
1545 self.__class__,
1546 magic_name,
1547 "use @observe and @unobserve instead.",
1548 )
1549 cb = getattr(self, magic_name)
1550 # Only append the magic method if it was not manually registered
1551 if cb not in callables:
1552 callables.append(_callback_wrapper(cb))
1554 # Call them all now
1555 # Traits catches and logs errors here. I allow them to raise
1556 for c in callables:
1557 # Bound methods have an additional 'self' argument.
1559 if isinstance(c, _CallbackWrapper):
1560 c = c.__call__
1561 elif isinstance(c, EventHandler) and c.name is not None:
1562 c = getattr(self, c.name)
1564 c(event)
1566 def _add_notifiers(self, handler, name, type):
1567 if name not in self._trait_notifiers:
1568 nlist: t.List[t.Any] = []
1569 self._trait_notifiers[name] = {type: nlist}
1570 else:
1571 if type not in self._trait_notifiers[name]:
1572 nlist = []
1573 self._trait_notifiers[name][type] = nlist
1574 else:
1575 nlist = self._trait_notifiers[name][type]
1576 if handler not in nlist:
1577 nlist.append(handler)
1579 def _remove_notifiers(self, handler, name, type):
1580 try:
1581 if handler is None:
1582 del self._trait_notifiers[name][type]
1583 else:
1584 self._trait_notifiers[name][type].remove(handler)
1585 except KeyError:
1586 pass
1588 def on_trait_change(self, handler=None, name=None, remove=False):
1589 """DEPRECATED: Setup a handler to be called when a trait changes.
1591 This is used to setup dynamic notifications of trait changes.
1593 Static handlers can be created by creating methods on a HasTraits
1594 subclass with the naming convention '_[traitname]_changed'. Thus,
1595 to create static handler for the trait 'a', create the method
1596 _a_changed(self, name, old, new) (fewer arguments can be used, see
1597 below).
1599 If `remove` is True and `handler` is not specified, all change
1600 handlers for the specified name are uninstalled.
1602 Parameters
1603 ----------
1604 handler : callable, None
1605 A callable that is called when a trait changes. Its
1606 signature can be handler(), handler(name), handler(name, new),
1607 handler(name, old, new), or handler(name, old, new, self).
1608 name : list, str, None
1609 If None, the handler will apply to all traits. If a list
1610 of str, handler will apply to all names in the list. If a
1611 str, the handler will apply just to that name.
1612 remove : bool
1613 If False (the default), then install the handler. If True
1614 then unintall it.
1615 """
1616 warn(
1617 "on_trait_change is deprecated in traitlets 4.1: use observe instead",
1618 DeprecationWarning,
1619 stacklevel=2,
1620 )
1621 if name is None:
1622 name = All
1623 if remove:
1624 self.unobserve(_callback_wrapper(handler), names=name)
1625 else:
1626 self.observe(_callback_wrapper(handler), names=name)
1628 def observe(self, handler, names=All, type="change"):
1629 """Setup a handler to be called when a trait changes.
1631 This is used to setup dynamic notifications of trait changes.
1633 Parameters
1634 ----------
1635 handler : callable
1636 A callable that is called when a trait changes. Its
1637 signature should be ``handler(change)``, where ``change`` is a
1638 dictionary. The change dictionary at least holds a 'type' key.
1639 * ``type``: the type of notification.
1640 Other keys may be passed depending on the value of 'type'. In the
1641 case where type is 'change', we also have the following keys:
1642 * ``owner`` : the HasTraits instance
1643 * ``old`` : the old value of the modified trait attribute
1644 * ``new`` : the new value of the modified trait attribute
1645 * ``name`` : the name of the modified trait attribute.
1646 names : list, str, All
1647 If names is All, the handler will apply to all traits. If a list
1648 of str, handler will apply to all names in the list. If a
1649 str, the handler will apply just to that name.
1650 type : str, All (default: 'change')
1651 The type of notification to filter by. If equal to All, then all
1652 notifications are passed to the observe handler.
1653 """
1654 names = parse_notifier_name(names)
1655 for n in names:
1656 self._add_notifiers(handler, n, type)
1658 def unobserve(self, handler, names=All, type="change"):
1659 """Remove a trait change handler.
1661 This is used to unregister handlers to trait change notifications.
1663 Parameters
1664 ----------
1665 handler : callable
1666 The callable called when a trait attribute changes.
1667 names : list, str, All (default: All)
1668 The names of the traits for which the specified handler should be
1669 uninstalled. If names is All, the specified handler is uninstalled
1670 from the list of notifiers corresponding to all changes.
1671 type : str or All (default: 'change')
1672 The type of notification to filter by. If All, the specified handler
1673 is uninstalled from the list of notifiers corresponding to all types.
1674 """
1675 names = parse_notifier_name(names)
1676 for n in names:
1677 self._remove_notifiers(handler, n, type)
1679 def unobserve_all(self, name=All):
1680 """Remove trait change handlers of any type for the specified name.
1681 If name is not specified, removes all trait notifiers."""
1682 if name is All:
1683 self._trait_notifiers: t.Dict[str, t.Any] = {}
1684 else:
1685 try:
1686 del self._trait_notifiers[name]
1687 except KeyError:
1688 pass
1690 def _register_validator(self, handler, names):
1691 """Setup a handler to be called when a trait should be cross validated.
1693 This is used to setup dynamic notifications for cross-validation.
1695 If a validator is already registered for any of the provided names, a
1696 TraitError is raised and no new validator is registered.
1698 Parameters
1699 ----------
1700 handler : callable
1701 A callable that is called when the given trait is cross-validated.
1702 Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
1703 with the following attributes/keys:
1704 * ``owner`` : the HasTraits instance
1705 * ``value`` : the proposed value for the modified trait attribute
1706 * ``trait`` : the TraitType instance associated with the attribute
1707 names : List of strings
1708 The names of the traits that should be cross-validated
1709 """
1710 for name in names:
1711 magic_name = "_%s_validate" % name
1712 if hasattr(self, magic_name):
1713 class_value = getattr(self.__class__, magic_name)
1714 if not isinstance(class_value, ValidateHandler):
1715 _deprecated_method(
1716 class_value,
1717 self.__class__,
1718 magic_name,
1719 "use @validate decorator instead.",
1720 )
1721 for name in names:
1722 self._trait_validators[name] = handler
1724 def add_traits(self, **traits):
1725 """Dynamically add trait attributes to the HasTraits instance."""
1726 cls = self.__class__
1727 attrs = {"__module__": cls.__module__}
1728 if hasattr(cls, "__qualname__"):
1729 # __qualname__ introduced in Python 3.3 (see PEP 3155)
1730 attrs["__qualname__"] = cls.__qualname__
1731 attrs.update(traits)
1732 self.__class__ = type(cls.__name__, (cls,), attrs)
1733 for trait in traits.values():
1734 trait.instance_init(self)
1736 def set_trait(self, name, value):
1737 """Forcibly sets trait attribute, including read-only attributes."""
1738 cls = self.__class__
1739 if not self.has_trait(name):
1740 raise TraitError(f"Class {cls.__name__} does not have a trait named {name}")
1741 else:
1742 getattr(cls, name).set(self, value)
1744 @classmethod
1745 def class_trait_names(cls, **metadata):
1746 """Get a list of all the names of this class' traits.
1748 This method is just like the :meth:`trait_names` method,
1749 but is unbound.
1750 """
1751 return list(cls.class_traits(**metadata))
1753 @classmethod
1754 def class_traits(cls, **metadata):
1755 """Get a ``dict`` of all the traits of this class. The dictionary
1756 is keyed on the name and the values are the TraitType objects.
1758 This method is just like the :meth:`traits` method, but is unbound.
1760 The TraitTypes returned don't know anything about the values
1761 that the various HasTrait's instances are holding.
1763 The metadata kwargs allow functions to be passed in which
1764 filter traits based on metadata values. The functions should
1765 take a single value as an argument and return a boolean. If
1766 any function returns False, then the trait is not included in
1767 the output. If a metadata key doesn't exist, None will be passed
1768 to the function.
1769 """
1770 traits = cls._traits.copy()
1772 if len(metadata) == 0:
1773 return traits
1775 result = {}
1776 for name, trait in traits.items():
1777 for meta_name, meta_eval in metadata.items():
1778 if not callable(meta_eval):
1779 meta_eval = _SimpleTest(meta_eval)
1780 if not meta_eval(trait.metadata.get(meta_name, None)):
1781 break
1782 else:
1783 result[name] = trait
1785 return result
1787 @classmethod
1788 def class_own_traits(cls, **metadata):
1789 """Get a dict of all the traitlets defined on this class, not a parent.
1791 Works like `class_traits`, except for excluding traits from parents.
1792 """
1793 sup = super(cls, cls)
1794 return {
1795 n: t
1796 for (n, t) in cls.class_traits(**metadata).items()
1797 if getattr(sup, n, None) is not t
1798 }
1800 def has_trait(self, name):
1801 """Returns True if the object has a trait with the specified name."""
1802 return name in self._traits
1804 def trait_has_value(self, name):
1805 """Returns True if the specified trait has a value.
1807 This will return false even if ``getattr`` would return a
1808 dynamically generated default value. These default values
1809 will be recognized as existing only after they have been
1810 generated.
1812 Example
1814 .. code-block:: python
1816 class MyClass(HasTraits):
1817 i = Int()
1819 mc = MyClass()
1820 assert not mc.trait_has_value("i")
1821 mc.i # generates a default value
1822 assert mc.trait_has_value("i")
1823 """
1824 return name in self._trait_values
1826 def trait_values(self, **metadata):
1827 """A ``dict`` of trait names and their values.
1829 The metadata kwargs allow functions to be passed in which
1830 filter traits based on metadata values. The functions should
1831 take a single value as an argument and return a boolean. If
1832 any function returns False, then the trait is not included in
1833 the output. If a metadata key doesn't exist, None will be passed
1834 to the function.
1836 Returns
1837 -------
1838 A ``dict`` of trait names and their values.
1840 Notes
1841 -----
1842 Trait values are retrieved via ``getattr``, any exceptions raised
1843 by traits or the operations they may trigger will result in the
1844 absence of a trait value in the result ``dict``.
1845 """
1846 return {name: getattr(self, name) for name in self.trait_names(**metadata)}
1848 def _get_trait_default_generator(self, name):
1849 """Return default generator for a given trait
1851 Walk the MRO to resolve the correct default generator according to inheritance.
1852 """
1853 method_name = "_%s_default" % name
1854 if method_name in self.__dict__:
1855 return getattr(self, method_name)
1856 if method_name in self.__class__.__dict__:
1857 return getattr(self.__class__, method_name)
1858 return self._all_trait_default_generators[name]
1860 def trait_defaults(self, *names, **metadata):
1861 """Return a trait's default value or a dictionary of them
1863 Notes
1864 -----
1865 Dynamically generated default values may
1866 depend on the current state of the object."""
1867 for n in names:
1868 if not self.has_trait(n):
1869 raise TraitError(f"'{n}' is not a trait of '{type(self).__name__}' instances")
1871 if len(names) == 1 and len(metadata) == 0:
1872 return self._get_trait_default_generator(names[0])(self)
1874 trait_names = self.trait_names(**metadata)
1875 trait_names.extend(names)
1877 defaults = {}
1878 for n in trait_names:
1879 defaults[n] = self._get_trait_default_generator(n)(self)
1880 return defaults
1882 def trait_names(self, **metadata):
1883 """Get a list of all the names of this class' traits."""
1884 return list(self.traits(**metadata))
1886 def traits(self, **metadata):
1887 """Get a ``dict`` of all the traits of this class. The dictionary
1888 is keyed on the name and the values are the TraitType objects.
1890 The TraitTypes returned don't know anything about the values
1891 that the various HasTrait's instances are holding.
1893 The metadata kwargs allow functions to be passed in which
1894 filter traits based on metadata values. The functions should
1895 take a single value as an argument and return a boolean. If
1896 any function returns False, then the trait is not included in
1897 the output. If a metadata key doesn't exist, None will be passed
1898 to the function.
1899 """
1900 traits = self._traits.copy()
1902 if len(metadata) == 0:
1903 return traits
1905 result = {}
1906 for name, trait in traits.items():
1907 for meta_name, meta_eval in metadata.items():
1908 if not callable(meta_eval):
1909 meta_eval = _SimpleTest(meta_eval)
1910 if not meta_eval(trait.metadata.get(meta_name, None)):
1911 break
1912 else:
1913 result[name] = trait
1915 return result
1917 def trait_metadata(self, traitname, key, default=None):
1918 """Get metadata values for trait by key."""
1919 try:
1920 trait = getattr(self.__class__, traitname)
1921 except AttributeError as e:
1922 raise TraitError(
1923 f"Class {self.__class__.__name__} does not have a trait named {traitname}"
1924 ) from e
1925 metadata_name = "_" + traitname + "_metadata"
1926 if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
1927 return getattr(self, metadata_name).get(key, default)
1928 else:
1929 return trait.metadata.get(key, default)
1931 @classmethod
1932 def class_own_trait_events(cls, name):
1933 """Get a dict of all event handlers defined on this class, not a parent.
1935 Works like ``event_handlers``, except for excluding traits from parents.
1936 """
1937 sup = super(cls, cls)
1938 return {
1939 n: e
1940 for (n, e) in cls.events(name).items() # type:ignore[attr-defined]
1941 if getattr(sup, n, None) is not e
1942 }
1944 @classmethod
1945 def trait_events(cls, name=None):
1946 """Get a ``dict`` of all the event handlers of this class.
1948 Parameters
1949 ----------
1950 name : str (default: None)
1951 The name of a trait of this class. If name is ``None`` then all
1952 the event handlers of this class will be returned instead.
1954 Returns
1955 -------
1956 The event handlers associated with a trait name, or all event handlers.
1957 """
1958 events = {}
1959 for k, v in getmembers(cls):
1960 if isinstance(v, EventHandler):
1961 if name is None:
1962 events[k] = v
1963 elif name in v.trait_names: # type:ignore[attr-defined]
1964 events[k] = v
1965 elif hasattr(v, "tags"):
1966 if cls.trait_names(**v.tags):
1967 events[k] = v
1968 return events
1971# -----------------------------------------------------------------------------
1972# Actual TraitTypes implementations/subclasses
1973# -----------------------------------------------------------------------------
1975# -----------------------------------------------------------------------------
1976# TraitTypes subclasses for handling classes and instances of classes
1977# -----------------------------------------------------------------------------
1980class ClassBasedTraitType(TraitType):
1981 """
1982 A trait with error reporting and string -> type resolution for Type,
1983 Instance and This.
1984 """
1986 def _resolve_string(self, string):
1987 """
1988 Resolve a string supplied for a type into an actual object.
1989 """
1990 return import_item(string)
1993class Type(ClassBasedTraitType):
1994 """A trait whose value must be a subclass of a specified class."""
1996 def __init__(self, default_value=Undefined, klass=None, **kwargs):
1997 """Construct a Type trait
1999 A Type trait specifies that its values must be subclasses of
2000 a particular class.
2002 If only ``default_value`` is given, it is used for the ``klass`` as
2003 well. If neither are given, both default to ``object``.
2005 Parameters
2006 ----------
2007 default_value : class, str or None
2008 The default value must be a subclass of klass. If an str,
2009 the str must be a fully specified class name, like 'foo.bar.Bah'.
2010 The string is resolved into real class, when the parent
2011 :class:`HasTraits` class is instantiated.
2012 klass : class, str [ default object ]
2013 Values of this trait must be a subclass of klass. The klass
2014 may be specified in a string like: 'foo.bar.MyClass'.
2015 The string is resolved into real class, when the parent
2016 :class:`HasTraits` class is instantiated.
2017 allow_none : bool [ default False ]
2018 Indicates whether None is allowed as an assignable value.
2019 **kwargs
2020 extra kwargs passed to `ClassBasedTraitType`
2021 """
2022 if default_value is Undefined:
2023 new_default_value = object if (klass is None) else klass
2024 else:
2025 new_default_value = default_value
2027 if klass is None:
2028 if (default_value is None) or (default_value is Undefined):
2029 klass = object
2030 else:
2031 klass = default_value
2033 if not (inspect.isclass(klass) or isinstance(klass, str)):
2034 raise TraitError("A Type trait must specify a class.")
2036 self.klass = klass
2038 super().__init__(new_default_value, **kwargs)
2040 def validate(self, obj, value):
2041 """Validates that the value is a valid object instance."""
2042 if isinstance(value, str):
2043 try:
2044 value = self._resolve_string(value)
2045 except ImportError as e:
2046 raise TraitError(
2047 "The '%s' trait of %s instance must be a type, but "
2048 "%r could not be imported" % (self.name, obj, value)
2049 ) from e
2050 try:
2051 if issubclass(value, self.klass): # type:ignore[arg-type]
2052 return value
2053 except Exception:
2054 pass
2056 self.error(obj, value)
2058 def info(self):
2059 """Returns a description of the trait."""
2060 if isinstance(self.klass, str):
2061 klass = self.klass
2062 else:
2063 klass = self.klass.__module__ + "." + self.klass.__name__
2064 result = "a subclass of '%s'" % klass
2065 if self.allow_none:
2066 return result + " or None"
2067 return result
2069 def instance_init(self, obj):
2070 # we can't do this in subclass_init because that
2071 # might be called before all imports are done.
2072 self._resolve_classes()
2074 def _resolve_classes(self):
2075 if isinstance(self.klass, str):
2076 self.klass = self._resolve_string(self.klass)
2077 if isinstance(self.default_value, str):
2078 self.default_value = self._resolve_string(self.default_value)
2080 def default_value_repr(self):
2081 value = self.default_value
2082 assert value is not None
2083 if isinstance(value, str):
2084 return repr(value)
2085 else:
2086 return repr(f"{value.__module__}.{value.__name__}")
2089class Instance(ClassBasedTraitType):
2090 """A trait whose value must be an instance of a specified class.
2092 The value can also be an instance of a subclass of the specified class.
2094 Subclasses can declare default classes by overriding the klass attribute
2095 """
2097 klass = None
2099 def __init__(self, klass=None, args=None, kw=None, **kwargs):
2100 """Construct an Instance trait.
2102 This trait allows values that are instances of a particular
2103 class or its subclasses. Our implementation is quite different
2104 from that of enthough.traits as we don't allow instances to be used
2105 for klass and we handle the ``args`` and ``kw`` arguments differently.
2107 Parameters
2108 ----------
2109 klass : class, str
2110 The class that forms the basis for the trait. Class names
2111 can also be specified as strings, like 'foo.bar.Bar'.
2112 args : tuple
2113 Positional arguments for generating the default value.
2114 kw : dict
2115 Keyword arguments for generating the default value.
2116 allow_none : bool [ default False ]
2117 Indicates whether None is allowed as a value.
2118 **kwargs
2119 Extra kwargs passed to `ClassBasedTraitType`
2121 Notes
2122 -----
2123 If both ``args`` and ``kw`` are None, then the default value is None.
2124 If ``args`` is a tuple and ``kw`` is a dict, then the default is
2125 created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
2126 None, the None is replaced by ``()`` or ``{}``, respectively.
2127 """
2128 if klass is None:
2129 klass = self.klass
2131 if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)):
2132 self.klass = klass
2133 else:
2134 raise TraitError("The klass attribute must be a class not: %r" % klass)
2136 if (kw is not None) and not isinstance(kw, dict):
2137 raise TraitError("The 'kw' argument must be a dict or None.")
2138 if (args is not None) and not isinstance(args, tuple):
2139 raise TraitError("The 'args' argument must be a tuple or None.")
2141 self.default_args = args
2142 self.default_kwargs = kw
2144 super().__init__(**kwargs)
2146 def validate(self, obj, value):
2147 assert self.klass is not None
2148 if isinstance(value, self.klass): # type:ignore[arg-type]
2149 return value
2150 else:
2151 self.error(obj, value)
2153 def info(self):
2154 if isinstance(self.klass, str):
2155 result = add_article(self.klass)
2156 else:
2157 result = describe("a", self.klass)
2158 if self.allow_none:
2159 result += " or None"
2160 return result
2162 def instance_init(self, obj):
2163 # we can't do this in subclass_init because that
2164 # might be called before all imports are done.
2165 self._resolve_classes()
2167 def _resolve_classes(self):
2168 if isinstance(self.klass, str):
2169 self.klass = self._resolve_string(self.klass)
2171 def make_dynamic_default(self):
2172 if (self.default_args is None) and (self.default_kwargs is None):
2173 return None
2174 assert self.klass is not None
2175 return self.klass(
2176 *(self.default_args or ()), **(self.default_kwargs or {})
2177 ) # type:ignore[operator]
2179 def default_value_repr(self):
2180 return repr(self.make_dynamic_default())
2182 def from_string(self, s):
2183 return _safe_literal_eval(s)
2186class ForwardDeclaredMixin:
2187 """
2188 Mixin for forward-declared versions of Instance and Type.
2189 """
2191 def _resolve_string(self, string):
2192 """
2193 Find the specified class name by looking for it in the module in which
2194 our this_class attribute was defined.
2195 """
2196 modname = self.this_class.__module__ # type:ignore[attr-defined]
2197 return import_item(".".join([modname, string]))
2200class ForwardDeclaredType(ForwardDeclaredMixin, Type):
2201 """
2202 Forward-declared version of Type.
2203 """
2205 pass
2208class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
2209 """
2210 Forward-declared version of Instance.
2211 """
2213 pass
2216class This(ClassBasedTraitType):
2217 """A trait for instances of the class containing this trait.
2219 Because how how and when class bodies are executed, the ``This``
2220 trait can only have a default value of None. This, and because we
2221 always validate default values, ``allow_none`` is *always* true.
2222 """
2224 info_text = "an instance of the same type as the receiver or None"
2226 def __init__(self, **kwargs):
2227 super().__init__(None, **kwargs)
2229 def validate(self, obj, value):
2230 # What if value is a superclass of obj.__class__? This is
2231 # complicated if it was the superclass that defined the This
2232 # trait.
2233 assert self.this_class is not None
2234 if isinstance(value, self.this_class) or (value is None):
2235 return value
2236 else:
2237 self.error(obj, value)
2240class Union(TraitType):
2241 """A trait type representing a Union type."""
2243 def __init__(self, trait_types, **kwargs):
2244 """Construct a Union trait.
2246 This trait allows values that are allowed by at least one of the
2247 specified trait types. A Union traitlet cannot have metadata on
2248 its own, besides the metadata of the listed types.
2250 Parameters
2251 ----------
2252 trait_types : sequence
2253 The list of trait types of length at least 1.
2254 **kwargs
2255 Extra kwargs passed to `TraitType`
2257 Notes
2258 -----
2259 Union([Float(), Bool(), Int()]) attempts to validate the provided values
2260 with the validation function of Float, then Bool, and finally Int.
2262 Parsing from string is ambiguous for container types which accept other
2263 collection-like literals (e.g. List accepting both `[]` and `()`
2264 precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
2265 you can modify behaviour of too permissive container traits by overriding
2266 ``_literal_from_string_pairs`` in subclasses.
2267 Similarly, parsing unions of numeric types is only unambiguous if
2268 types are provided in order of increasing permissiveness, e.g.
2269 ``Union([Int(), Float()])`` (since floats accept integer-looking values).
2270 """
2271 self.trait_types = list(trait_types)
2272 self.info_text = " or ".join([tt.info() for tt in self.trait_types])
2273 super().__init__(**kwargs)
2275 def default(self, obj=None):
2276 default = super().default(obj)
2277 for trait in self.trait_types:
2278 if default is Undefined:
2279 default = trait.default(obj)
2280 else:
2281 break
2282 return default
2284 def class_init(self, cls, name):
2285 for trait_type in reversed(self.trait_types):
2286 trait_type.class_init(cls, None)
2287 super().class_init(cls, name)
2289 def subclass_init(self, cls):
2290 for trait_type in reversed(self.trait_types):
2291 trait_type.subclass_init(cls)
2292 # explicitly not calling super().subclass_init(cls)
2293 # to opt out of instance_init
2295 def validate(self, obj, value):
2296 with obj.cross_validation_lock:
2297 for trait_type in self.trait_types:
2298 try:
2299 v = trait_type._validate(obj, value)
2300 # In the case of an element trait, the name is None
2301 if self.name is not None:
2302 setattr(obj, "_" + self.name + "_metadata", trait_type.metadata)
2303 return v
2304 except TraitError:
2305 continue
2306 self.error(obj, value)
2308 def __or__(self, other):
2309 if isinstance(other, Union):
2310 return Union(self.trait_types + other.trait_types)
2311 else:
2312 return Union(self.trait_types + [other])
2314 def from_string(self, s):
2315 for trait_type in self.trait_types:
2316 try:
2317 v = trait_type.from_string(s)
2318 return trait_type.validate(None, v)
2319 except (TraitError, ValueError):
2320 continue
2321 return super().from_string(s)
2324# -----------------------------------------------------------------------------
2325# Basic TraitTypes implementations/subclasses
2326# -----------------------------------------------------------------------------
2329class Any(TraitType):
2330 """A trait which allows any value."""
2332 default_value: t.Optional[t.Any] = None
2333 allow_none = True
2334 info_text = "any value"
2336 def subclass_init(self, cls):
2337 pass # fully opt out of instance_init
2340def _validate_bounds(trait, obj, value):
2341 """
2342 Validate that a number to be applied to a trait is between bounds.
2344 If value is not between min_bound and max_bound, this raises a
2345 TraitError with an error message appropriate for this trait.
2346 """
2347 if trait.min is not None and value < trait.min:
2348 raise TraitError(
2349 "The value of the '{name}' trait of {klass} instance should "
2350 "not be less than {min_bound}, but a value of {value} was "
2351 "specified".format(
2352 name=trait.name, klass=class_of(obj), value=value, min_bound=trait.min
2353 )
2354 )
2355 if trait.max is not None and value > trait.max:
2356 raise TraitError(
2357 "The value of the '{name}' trait of {klass} instance should "
2358 "not be greater than {max_bound}, but a value of {value} was "
2359 "specified".format(
2360 name=trait.name, klass=class_of(obj), value=value, max_bound=trait.max
2361 )
2362 )
2363 return value
2366class Int(TraitType):
2367 """An int trait."""
2369 default_value = 0
2370 info_text = "an int"
2372 def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
2373 self.min = kwargs.pop("min", None)
2374 self.max = kwargs.pop("max", None)
2375 super().__init__(default_value=default_value, allow_none=allow_none, **kwargs)
2377 def validate(self, obj, value):
2378 if not isinstance(value, int):
2379 self.error(obj, value)
2380 return _validate_bounds(self, obj, value)
2382 def from_string(self, s):
2383 if self.allow_none and s == "None":
2384 return None
2385 return int(s)
2387 def subclass_init(self, cls):
2388 pass # fully opt out of instance_init
2391class CInt(Int):
2392 """A casting version of the int trait."""
2394 def validate(self, obj, value):
2395 try:
2396 value = int(value)
2397 except Exception:
2398 self.error(obj, value)
2399 return _validate_bounds(self, obj, value)
2402Long, CLong = Int, CInt
2403Integer = Int
2406class Float(TraitType):
2407 """A float trait."""
2409 default_value = 0.0
2410 info_text = "a float"
2412 def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
2413 self.min = kwargs.pop("min", -float("inf"))
2414 self.max = kwargs.pop("max", float("inf"))
2415 super().__init__(default_value=default_value, allow_none=allow_none, **kwargs)
2417 def validate(self, obj, value):
2418 if isinstance(value, int):
2419 value = float(value)
2420 if not isinstance(value, float):
2421 self.error(obj, value)
2422 return _validate_bounds(self, obj, value)
2424 def from_string(self, s):
2425 if self.allow_none and s == "None":
2426 return None
2427 return float(s)
2429 def subclass_init(self, cls):
2430 pass # fully opt out of instance_init
2433class CFloat(Float):
2434 """A casting version of the float trait."""
2436 def validate(self, obj, value):
2437 try:
2438 value = float(value)
2439 except Exception:
2440 self.error(obj, value)
2441 return _validate_bounds(self, obj, value)
2444class Complex(TraitType):
2445 """A trait for complex numbers."""
2447 default_value = 0.0 + 0.0j
2448 info_text = "a complex number"
2450 def validate(self, obj, value):
2451 if isinstance(value, complex):
2452 return value
2453 if isinstance(value, (float, int)):
2454 return complex(value)
2455 self.error(obj, value)
2457 def from_string(self, s):
2458 if self.allow_none and s == "None":
2459 return None
2460 return complex(s)
2462 def subclass_init(self, cls):
2463 pass # fully opt out of instance_init
2466class CComplex(Complex):
2467 """A casting version of the complex number trait."""
2469 def validate(self, obj, value):
2470 try:
2471 return complex(value)
2472 except Exception:
2473 self.error(obj, value)
2476# We should always be explicit about whether we're using bytes or unicode, both
2477# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
2478# we don't have a Str type.
2479class Bytes(TraitType):
2480 """A trait for byte strings."""
2482 default_value = b""
2483 info_text = "a bytes object"
2485 def validate(self, obj, value):
2486 if isinstance(value, bytes):
2487 return value
2488 self.error(obj, value)
2490 def from_string(self, s):
2491 if self.allow_none and s == "None":
2492 return None
2493 if len(s) >= 3:
2494 # handle deprecated b"string"
2495 for quote in ('"', "'"):
2496 if s[:2] == f"b{quote}" and s[-1] == quote:
2497 old_s = s
2498 s = s[2:-1]
2499 warn(
2500 "Supporting extra quotes around Bytes is deprecated in traitlets 5.0. "
2501 "Use %r instead of %r." % (s, old_s),
2502 FutureWarning,
2503 )
2504 break
2505 return s.encode("utf8")
2507 def subclass_init(self, cls):
2508 pass # fully opt out of instance_init
2511class CBytes(Bytes):
2512 """A casting version of the byte string trait."""
2514 def validate(self, obj, value):
2515 try:
2516 return bytes(value)
2517 except Exception:
2518 self.error(obj, value)
2521class Unicode(TraitType):
2522 """A trait for unicode strings."""
2524 default_value = ""
2525 info_text = "a unicode string"
2527 def validate(self, obj, value):
2528 if isinstance(value, str):
2529 return value
2530 if isinstance(value, bytes):
2531 try:
2532 return value.decode("ascii", "strict")
2533 except UnicodeDecodeError as e:
2534 msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
2535 raise TraitError(msg.format(value, self.name, class_of(obj))) from e
2536 self.error(obj, value)
2538 def from_string(self, s):
2539 if self.allow_none and s == "None":
2540 return None
2541 s = os.path.expanduser(s)
2542 if len(s) >= 2:
2543 # handle deprecated "1"
2544 for c in ('"', "'"):
2545 if s[0] == s[-1] == c:
2546 old_s = s
2547 s = s[1:-1]
2548 warn(
2549 "Supporting extra quotes around strings is deprecated in traitlets 5.0. "
2550 "You can use %r instead of %r if you require traitlets >=5." % (s, old_s),
2551 FutureWarning,
2552 )
2553 return s
2555 def subclass_init(self, cls):
2556 pass # fully opt out of instance_init
2559class CUnicode(Unicode):
2560 """A casting version of the unicode trait."""
2562 def validate(self, obj, value):
2563 try:
2564 return str(value)
2565 except Exception:
2566 self.error(obj, value)
2569class ObjectName(TraitType):
2570 """A string holding a valid object name in this version of Python.
2572 This does not check that the name exists in any scope."""
2574 info_text = "a valid object identifier in Python"
2576 coerce_str = staticmethod(lambda _, s: s) # type:ignore[no-any-return]
2578 def validate(self, obj, value):
2579 value = self.coerce_str(obj, value)
2581 if isinstance(value, str) and isidentifier(value):
2582 return value
2583 self.error(obj, value)
2585 def from_string(self, s):
2586 if self.allow_none and s == "None":
2587 return None
2588 return s
2591class DottedObjectName(ObjectName):
2592 """A string holding a valid dotted object name in Python, such as A.b3._c"""
2594 def validate(self, obj, value):
2595 value = self.coerce_str(obj, value)
2597 if isinstance(value, str) and all(isidentifier(a) for a in value.split(".")):
2598 return value
2599 self.error(obj, value)
2602class Bool(TraitType):
2603 """A boolean (True, False) trait."""
2605 default_value = False
2606 info_text = "a boolean"
2608 def validate(self, obj, value):
2609 if isinstance(value, bool):
2610 return value
2611 elif isinstance(value, int):
2612 if value == 1:
2613 return True
2614 elif value == 0:
2615 return False
2616 self.error(obj, value)
2618 def from_string(self, s):
2619 if self.allow_none and s == "None":
2620 return None
2621 s = s.lower()
2622 if s in {"true", "1"}:
2623 return True
2624 elif s in {"false", "0"}:
2625 return False
2626 else:
2627 raise ValueError("%r is not 1, 0, true, or false")
2629 def subclass_init(self, cls):
2630 pass # fully opt out of instance_init
2632 def argcompleter(self, **kwargs):
2633 """Completion hints for argcomplete"""
2634 completions = ["true", "1", "false", "0"]
2635 if self.allow_none:
2636 completions.append("None")
2637 return completions
2640class CBool(Bool):
2641 """A casting version of the boolean trait."""
2643 def validate(self, obj, value):
2644 try:
2645 return bool(value)
2646 except Exception:
2647 self.error(obj, value)
2650class Enum(TraitType):
2651 """An enum whose value must be in a given sequence."""
2653 def __init__(self, values, default_value=Undefined, **kwargs):
2654 self.values = values
2655 if kwargs.get("allow_none", False) and default_value is Undefined:
2656 default_value = None
2657 super().__init__(default_value, **kwargs)
2659 def validate(self, obj, value):
2660 if value in self.values:
2661 return value
2662 self.error(obj, value)
2664 def _choices_str(self, as_rst=False):
2665 """Returns a description of the trait choices (not none)."""
2666 choices = self.values
2667 if as_rst:
2668 choices = "|".join("``%r``" % x for x in choices)
2669 else:
2670 choices = repr(list(choices))
2671 return choices
2673 def _info(self, as_rst=False):
2674 """Returns a description of the trait."""
2675 none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
2676 return f"any of {self._choices_str(as_rst)}{none}"
2678 def info(self):
2679 return self._info(as_rst=False)
2681 def info_rst(self):
2682 return self._info(as_rst=True)
2684 def from_string(self, s):
2685 try:
2686 return self.validate(None, s)
2687 except TraitError:
2688 return _safe_literal_eval(s)
2690 def subclass_init(self, cls):
2691 pass # fully opt out of instance_init
2693 def argcompleter(self, **kwargs):
2694 """Completion hints for argcomplete"""
2695 return [str(v) for v in self.values]
2698class CaselessStrEnum(Enum):
2699 """An enum of strings where the case should be ignored."""
2701 def __init__(self, values, default_value=Undefined, **kwargs):
2702 super().__init__(values, default_value=default_value, **kwargs)
2704 def validate(self, obj, value):
2705 if not isinstance(value, str):
2706 self.error(obj, value)
2708 for v in self.values:
2709 if v.lower() == value.lower():
2710 return v
2711 self.error(obj, value)
2713 def _info(self, as_rst=False):
2714 """Returns a description of the trait."""
2715 none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
2716 return f"any of {self._choices_str(as_rst)} (case-insensitive){none}"
2718 def info(self):
2719 return self._info(as_rst=False)
2721 def info_rst(self):
2722 return self._info(as_rst=True)
2725class FuzzyEnum(Enum):
2726 """An case-ignoring enum matching choices by unique prefixes/substrings."""
2728 case_sensitive = False
2729 #: If True, choices match anywhere in the string, otherwise match prefixes.
2730 substring_matching = False
2732 def __init__(
2733 self,
2734 values,
2735 default_value=Undefined,
2736 case_sensitive=False,
2737 substring_matching=False,
2738 **kwargs,
2739 ):
2740 self.case_sensitive = case_sensitive
2741 self.substring_matching = substring_matching
2742 super().__init__(values, default_value=default_value, **kwargs)
2744 def validate(self, obj, value):
2745 if not isinstance(value, str):
2746 self.error(obj, value)
2748 conv_func = (lambda c: c) if self.case_sensitive else lambda c: c.lower()
2749 substring_matching = self.substring_matching
2750 match_func = (
2751 (lambda v, c: v in c)
2752 if substring_matching
2753 else (lambda v, c: c.startswith(v)) # type:ignore[no-any-return]
2754 )
2755 value = conv_func(value)
2756 choices = self.values
2757 matches = [match_func(value, conv_func(c)) for c in choices]
2758 if sum(matches) == 1:
2759 for v, m in zip(choices, matches):
2760 if m:
2761 return v
2763 self.error(obj, value)
2765 def _info(self, as_rst=False):
2766 """Returns a description of the trait."""
2767 none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
2768 case = "sensitive" if self.case_sensitive else "insensitive"
2769 substr = "substring" if self.substring_matching else "prefix"
2770 return f"any case-{case} {substr} of {self._choices_str(as_rst)}{none}"
2772 def info(self):
2773 return self._info(as_rst=False)
2775 def info_rst(self):
2776 return self._info(as_rst=True)
2779class Container(Instance):
2780 """An instance of a container (list, set, etc.)
2782 To be subclassed by overriding klass.
2783 """
2785 klass: t.Optional[t.Union[str, t.Type[t.Any]]] = None
2786 _cast_types: t.Any = ()
2787 _valid_defaults = SequenceTypes
2788 _trait = None
2789 _literal_from_string_pairs: t.Any = ("[]", "()")
2791 def __init__(self, trait=None, default_value=Undefined, **kwargs):
2792 """Create a container trait type from a list, set, or tuple.
2794 The default value is created by doing ``List(default_value)``,
2795 which creates a copy of the ``default_value``.
2797 ``trait`` can be specified, which restricts the type of elements
2798 in the container to that TraitType.
2800 If only one arg is given and it is not a Trait, it is taken as
2801 ``default_value``:
2803 ``c = List([1, 2, 3])``
2805 Parameters
2806 ----------
2807 trait : TraitType [ optional ]
2808 the type for restricting the contents of the Container. If unspecified,
2809 types are not checked.
2810 default_value : SequenceType [ optional ]
2811 The default value for the Trait. Must be list/tuple/set, and
2812 will be cast to the container type.
2813 allow_none : bool [ default False ]
2814 Whether to allow the value to be None
2815 **kwargs : any
2816 further keys for extensions to the Trait (e.g. config)
2818 """
2820 # allow List([values]):
2821 if trait is not None and default_value is Undefined and not is_trait(trait):
2822 default_value = trait
2823 trait = None
2825 if default_value is None and not kwargs.get("allow_none", False):
2826 # improve backward-compatibility for possible subclasses
2827 # specifying default_value=None as default,
2828 # keeping 'unspecified' behavior (i.e. empty container)
2829 warn(
2830 f"Specifying {self.__class__.__name__}(default_value=None)"
2831 " for no default is deprecated in traitlets 5.0.5."
2832 " Use default_value=Undefined",
2833 DeprecationWarning,
2834 stacklevel=2,
2835 )
2836 default_value = Undefined
2838 if default_value is Undefined:
2839 args: t.Any = ()
2840 elif default_value is None:
2841 # default_value back on kwargs for super() to handle
2842 args = ()
2843 kwargs["default_value"] = None
2844 elif isinstance(default_value, self._valid_defaults):
2845 args = (default_value,)
2846 else:
2847 raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
2849 if is_trait(trait):
2850 if isinstance(trait, type):
2851 warn(
2852 "Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
2853 " Passing types is deprecated in traitlets 4.1.",
2854 DeprecationWarning,
2855 stacklevel=3,
2856 )
2857 self._trait = trait() if isinstance(trait, type) else trait
2858 elif trait is not None:
2859 raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
2861 super().__init__(klass=self.klass, args=args, **kwargs)
2863 def validate(self, obj, value):
2864 if isinstance(value, self._cast_types):
2865 assert self.klass is not None
2866 value = self.klass(value) # type:ignore[operator]
2867 value = super().validate(obj, value)
2868 if value is None:
2869 return value
2871 value = self.validate_elements(obj, value)
2873 return value
2875 def validate_elements(self, obj, value):
2876 validated = []
2877 if self._trait is None or isinstance(self._trait, Any):
2878 return value
2879 for v in value:
2880 try:
2881 v = self._trait._validate(obj, v)
2882 except TraitError as error:
2883 self.error(obj, v, error)
2884 else:
2885 validated.append(v)
2886 assert self.klass is not None
2887 return self.klass(validated) # type:ignore[operator]
2889 def class_init(self, cls, name):
2890 if isinstance(self._trait, TraitType):
2891 self._trait.class_init(cls, None)
2892 super().class_init(cls, name)
2894 def subclass_init(self, cls):
2895 if isinstance(self._trait, TraitType):
2896 self._trait.subclass_init(cls)
2897 # explicitly not calling super().subclass_init(cls)
2898 # to opt out of instance_init
2900 def from_string(self, s):
2901 """Load value from a single string"""
2902 if not isinstance(s, str):
2903 raise TraitError(f"Expected string, got {s!r}")
2904 try:
2905 test = literal_eval(s)
2906 except Exception:
2907 test = None
2908 return self.validate(None, test)
2910 def from_string_list(self, s_list):
2911 """Return the value from a list of config strings
2913 This is where we parse CLI configuration
2914 """
2915 assert self.klass is not None
2916 if len(s_list) == 1:
2917 # check for deprecated --Class.trait="['a', 'b', 'c']"
2918 r = s_list[0]
2919 if r == "None" and self.allow_none:
2920 return None
2921 if len(r) >= 2 and any(
2922 r.startswith(start) and r.endswith(end)
2923 for start, end in self._literal_from_string_pairs
2924 ):
2925 if self.this_class:
2926 clsname = self.this_class.__name__ + "."
2927 else:
2928 clsname = ""
2929 assert self.name is not None
2930 warn(
2931 "--{0}={1} for containers is deprecated in traitlets 5.0. "
2932 "You can pass `--{0} item` ... multiple times to add items to a list.".format(
2933 clsname + self.name, r
2934 ),
2935 FutureWarning,
2936 )
2937 return self.klass(literal_eval(r)) # type:ignore[operator]
2938 sig = inspect.signature(self.item_from_string)
2939 if "index" in sig.parameters:
2940 item_from_string = self.item_from_string
2941 else:
2942 # backward-compat: allow item_from_string to ignore index arg
2943 item_from_string = lambda s, index=None: self.item_from_string(s) # noqa[E371]
2945 return self.klass(
2946 [item_from_string(s, index=idx) for idx, s in enumerate(s_list)]
2947 ) # type:ignore[operator]
2949 def item_from_string(self, s, index=None):
2950 """Cast a single item from a string
2952 Evaluated when parsing CLI configuration from a string
2953 """
2954 if self._trait:
2955 return self._trait.from_string(s)
2956 else:
2957 return s
2960class List(Container):
2961 """An instance of a Python list."""
2963 klass = list
2964 _cast_types: t.Any = (tuple,)
2966 def __init__(
2967 self,
2968 trait=None,
2969 default_value=Undefined,
2970 minlen=0,
2971 maxlen=sys.maxsize,
2972 **kwargs,
2973 ):
2974 """Create a List trait type from a list, set, or tuple.
2976 The default value is created by doing ``list(default_value)``,
2977 which creates a copy of the ``default_value``.
2979 ``trait`` can be specified, which restricts the type of elements
2980 in the container to that TraitType.
2982 If only one arg is given and it is not a Trait, it is taken as
2983 ``default_value``:
2985 ``c = List([1, 2, 3])``
2987 Parameters
2988 ----------
2989 trait : TraitType [ optional ]
2990 the type for restricting the contents of the Container.
2991 If unspecified, types are not checked.
2992 default_value : SequenceType [ optional ]
2993 The default value for the Trait. Must be list/tuple/set, and
2994 will be cast to the container type.
2995 minlen : Int [ default 0 ]
2996 The minimum length of the input list
2997 maxlen : Int [ default sys.maxsize ]
2998 The maximum length of the input list
2999 """
3000 self._minlen = minlen
3001 self._maxlen = maxlen
3002 super().__init__(trait=trait, default_value=default_value, **kwargs)
3004 def length_error(self, obj, value):
3005 e = (
3006 "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified."
3007 % (self.name, class_of(obj), self._minlen, self._maxlen, value)
3008 )
3009 raise TraitError(e)
3011 def validate_elements(self, obj, value):
3012 length = len(value)
3013 if length < self._minlen or length > self._maxlen:
3014 self.length_error(obj, value)
3016 return super().validate_elements(obj, value)
3018 def set(self, obj, value):
3019 if isinstance(value, str):
3020 return super().set(obj, [value])
3021 else:
3022 return super().set(obj, value)
3025class Set(List):
3026 """An instance of a Python set."""
3028 klass = set # type:ignore[assignment]
3029 _cast_types = (tuple, list)
3031 _literal_from_string_pairs = ("[]", "()", "{}")
3033 # Redefine __init__ just to make the docstring more accurate.
3034 def __init__(
3035 self,
3036 trait=None,
3037 default_value=Undefined,
3038 minlen=0,
3039 maxlen=sys.maxsize,
3040 **kwargs,
3041 ):
3042 """Create a Set trait type from a list, set, or tuple.
3044 The default value is created by doing ``set(default_value)``,
3045 which creates a copy of the ``default_value``.
3047 ``trait`` can be specified, which restricts the type of elements
3048 in the container to that TraitType.
3050 If only one arg is given and it is not a Trait, it is taken as
3051 ``default_value``:
3053 ``c = Set({1, 2, 3})``
3055 Parameters
3056 ----------
3057 trait : TraitType [ optional ]
3058 the type for restricting the contents of the Container.
3059 If unspecified, types are not checked.
3060 default_value : SequenceType [ optional ]
3061 The default value for the Trait. Must be list/tuple/set, and
3062 will be cast to the container type.
3063 minlen : Int [ default 0 ]
3064 The minimum length of the input list
3065 maxlen : Int [ default sys.maxsize ]
3066 The maximum length of the input list
3067 """
3068 super().__init__(trait, default_value, minlen, maxlen, **kwargs)
3070 def default_value_repr(self):
3071 # Ensure default value is sorted for a reproducible build
3072 list_repr = repr(sorted(self.make_dynamic_default()))
3073 if list_repr == "[]":
3074 return "set()"
3075 return "{" + list_repr[1:-1] + "}"
3078class Tuple(Container):
3079 """An instance of a Python tuple."""
3081 klass = tuple
3082 _cast_types = (list,)
3084 def __init__(self, *traits, **kwargs):
3085 """Create a tuple from a list, set, or tuple.
3087 Create a fixed-type tuple with Traits:
3089 ``t = Tuple(Int(), Str(), CStr())``
3091 would be length 3, with Int,Str,CStr for each element.
3093 If only one arg is given and it is not a Trait, it is taken as
3094 default_value:
3096 ``t = Tuple((1, 2, 3))``
3098 Otherwise, ``default_value`` *must* be specified by keyword.
3100 Parameters
3101 ----------
3102 *traits : TraitTypes [ optional ]
3103 the types for restricting the contents of the Tuple. If unspecified,
3104 types are not checked. If specified, then each positional argument
3105 corresponds to an element of the tuple. Tuples defined with traits
3106 are of fixed length.
3107 default_value : SequenceType [ optional ]
3108 The default value for the Tuple. Must be list/tuple/set, and
3109 will be cast to a tuple. If ``traits`` are specified,
3110 ``default_value`` must conform to the shape and type they specify.
3111 **kwargs
3112 Other kwargs passed to `Container`
3113 """
3114 default_value = kwargs.pop("default_value", Undefined)
3115 # allow Tuple((values,)):
3116 if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
3117 default_value = traits[0]
3118 traits = ()
3120 if default_value is None and not kwargs.get("allow_none", False):
3121 # improve backward-compatibility for possible subclasses
3122 # specifying default_value=None as default,
3123 # keeping 'unspecified' behavior (i.e. empty container)
3124 warn(
3125 f"Specifying {self.__class__.__name__}(default_value=None)"
3126 " for no default is deprecated in traitlets 5.0.5."
3127 " Use default_value=Undefined",
3128 DeprecationWarning,
3129 stacklevel=2,
3130 )
3131 default_value = Undefined
3133 if default_value is Undefined:
3134 args: t.Any = ()
3135 elif default_value is None:
3136 # default_value back on kwargs for super() to handle
3137 args = ()
3138 kwargs["default_value"] = None
3139 elif isinstance(default_value, self._valid_defaults):
3140 args = (default_value,)
3141 else:
3142 raise TypeError(f"default value of {self.__class__.__name__} was {default_value}")
3144 self._traits = []
3145 for trait in traits:
3146 if isinstance(trait, type):
3147 warn(
3148 "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
3149 " Passing types is deprecated in traitlets 4.1.",
3150 DeprecationWarning,
3151 stacklevel=2,
3152 )
3153 trait = trait()
3154 self._traits.append(trait)
3156 if self._traits and (default_value is None or default_value is Undefined):
3157 # don't allow default to be an empty container if length is specified
3158 args = None
3159 super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
3161 def item_from_string(self, s, index):
3162 """Cast a single item from a string
3164 Evaluated when parsing CLI configuration from a string
3165 """
3166 if not self._traits or index >= len(self._traits):
3167 # return s instead of raising index error
3168 # length errors will be raised later on validation
3169 return s
3170 return self._traits[index].from_string(s)
3172 def validate_elements(self, obj, value):
3173 if not self._traits:
3174 # nothing to validate
3175 return value
3176 if len(value) != len(self._traits):
3177 e = (
3178 "The '%s' trait of %s instance requires %i elements, but a value of %s was specified."
3179 % (self.name, class_of(obj), len(self._traits), repr_type(value))
3180 )
3181 raise TraitError(e)
3183 validated = []
3184 for trait, v in zip(self._traits, value):
3185 try:
3186 v = trait._validate(obj, v)
3187 except TraitError as error:
3188 self.error(obj, v, error)
3189 else:
3190 validated.append(v)
3191 return tuple(validated)
3193 def class_init(self, cls, name):
3194 for trait in self._traits:
3195 if isinstance(trait, TraitType):
3196 trait.class_init(cls, None)
3197 super(Container, self).class_init(cls, name)
3199 def subclass_init(self, cls):
3200 for trait in self._traits:
3201 if isinstance(trait, TraitType):
3202 trait.subclass_init(cls)
3203 # explicitly not calling super().subclass_init(cls)
3204 # to opt out of instance_init
3207class Dict(Instance):
3208 """An instance of a Python dict.
3210 One or more traits can be passed to the constructor
3211 to validate the keys and/or values of the dict.
3212 If you need more detailed validation,
3213 you may use a custom validator method.
3215 .. versionchanged:: 5.0
3216 Added key_trait for validating dict keys.
3218 .. versionchanged:: 5.0
3219 Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``.
3220 """
3222 _value_trait = None
3223 _key_trait = None
3225 def __init__(
3226 self,
3227 value_trait=None,
3228 per_key_traits=None,
3229 key_trait=None,
3230 default_value=Undefined,
3231 **kwargs,
3232 ):
3233 """Create a dict trait type from a Python dict.
3235 The default value is created by doing ``dict(default_value)``,
3236 which creates a copy of the ``default_value``.
3238 Parameters
3239 ----------
3240 value_trait : TraitType [ optional ]
3241 The specified trait type to check and use to restrict the values of
3242 the dict. If unspecified, values are not checked.
3243 per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ]
3244 A Python dictionary containing the types that are valid for
3245 restricting the values of the dict on a per-key basis.
3246 Each value in this dict should be a Trait for validating
3247 key_trait : TraitType [ optional, keyword-only ]
3248 The type for restricting the keys of the dict. If
3249 unspecified, the types of the keys are not checked.
3250 default_value : SequenceType [ optional, keyword-only ]
3251 The default value for the Dict. Must be dict, tuple, or None, and
3252 will be cast to a dict if not None. If any key or value traits are specified,
3253 the `default_value` must conform to the constraints.
3255 Examples
3256 --------
3257 a dict whose values must be text
3258 >>> d = Dict(Unicode())
3260 d2['n'] must be an integer
3261 d2['s'] must be text
3262 >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()})
3264 d3's keys must be text
3265 d3's values must be integers
3266 >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())
3268 """
3270 # handle deprecated keywords
3271 trait = kwargs.pop("trait", None)
3272 if trait is not None:
3273 if value_trait is not None:
3274 raise TypeError(
3275 "Found a value for both `value_trait` and its deprecated alias `trait`."
3276 )
3277 value_trait = trait
3278 warn(
3279 "Keyword `trait` is deprecated in traitlets 5.0, use `value_trait` instead",
3280 DeprecationWarning,
3281 stacklevel=2,
3282 )
3283 traits = kwargs.pop("traits", None)
3284 if traits is not None:
3285 if per_key_traits is not None:
3286 raise TypeError(
3287 "Found a value for both `per_key_traits` and its deprecated alias `traits`."
3288 )
3289 per_key_traits = traits
3290 warn(
3291 "Keyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` instead",
3292 DeprecationWarning,
3293 stacklevel=2,
3294 )
3296 # Handling positional arguments
3297 if default_value is Undefined and value_trait is not None:
3298 if not is_trait(value_trait):
3299 default_value = value_trait
3300 value_trait = None
3302 if key_trait is None and per_key_traits is not None:
3303 if is_trait(per_key_traits):
3304 key_trait = per_key_traits
3305 per_key_traits = None
3307 # Handling default value
3308 if default_value is Undefined:
3309 default_value = {}
3310 if default_value is None:
3311 args: t.Any = None
3312 elif isinstance(default_value, dict):
3313 args = (default_value,)
3314 elif isinstance(default_value, SequenceTypes):
3315 args = (default_value,)
3316 else:
3317 raise TypeError("default value of Dict was %s" % default_value)
3319 # Case where a type of TraitType is provided rather than an instance
3320 if is_trait(value_trait):
3321 if isinstance(value_trait, type):
3322 warn(
3323 "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
3324 " Passing types is deprecated in traitlets 4.1.",
3325 DeprecationWarning,
3326 stacklevel=2,
3327 )
3328 value_trait = value_trait()
3329 self._value_trait = value_trait
3330 elif value_trait is not None:
3331 raise TypeError(
3332 "`value_trait` must be a Trait or None, got %s" % repr_type(value_trait)
3333 )
3335 if is_trait(key_trait):
3336 if isinstance(key_trait, type):
3337 warn(
3338 "Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
3339 " Passing types is deprecated in traitlets 4.1.",
3340 DeprecationWarning,
3341 stacklevel=2,
3342 )
3343 key_trait = key_trait()
3344 self._key_trait = key_trait
3345 elif key_trait is not None:
3346 raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait))
3348 self._per_key_traits = per_key_traits
3350 super().__init__(klass=dict, args=args, **kwargs)
3352 def element_error(self, obj, element, validator, side="Values"):
3353 e = (
3354 side
3355 + " of the '%s' trait of %s instance must be %s, but a value of %s was specified."
3356 % (self.name, class_of(obj), validator.info(), repr_type(element))
3357 )
3358 raise TraitError(e)
3360 def validate(self, obj, value):
3361 value = super().validate(obj, value)
3362 if value is None:
3363 return value
3364 value = self.validate_elements(obj, value)
3365 return value
3367 def validate_elements(self, obj, value):
3368 per_key_override = self._per_key_traits or {}
3369 key_trait = self._key_trait
3370 value_trait = self._value_trait
3371 if not (key_trait or value_trait or per_key_override):
3372 return value
3374 validated = {}
3375 for key in value:
3376 v = value[key]
3377 if key_trait:
3378 try:
3379 key = key_trait._validate(obj, key)
3380 except TraitError:
3381 self.element_error(obj, key, key_trait, "Keys")
3382 active_value_trait = per_key_override.get(key, value_trait)
3383 if active_value_trait:
3384 try:
3385 v = active_value_trait._validate(obj, v)
3386 except TraitError:
3387 self.element_error(obj, v, active_value_trait, "Values")
3388 validated[key] = v
3390 return self.klass(validated) # type:ignore
3392 def class_init(self, cls, name):
3393 if isinstance(self._value_trait, TraitType):
3394 self._value_trait.class_init(cls, None)
3395 if isinstance(self._key_trait, TraitType):
3396 self._key_trait.class_init(cls, None)
3397 if self._per_key_traits is not None:
3398 for trait in self._per_key_traits.values():
3399 trait.class_init(cls, None)
3400 super().class_init(cls, name)
3402 def subclass_init(self, cls):
3403 if isinstance(self._value_trait, TraitType):
3404 self._value_trait.subclass_init(cls)
3405 if isinstance(self._key_trait, TraitType):
3406 self._key_trait.subclass_init(cls)
3407 if self._per_key_traits is not None:
3408 for trait in self._per_key_traits.values():
3409 trait.subclass_init(cls)
3410 # explicitly not calling super().subclass_init(cls)
3411 # to opt out of instance_init
3413 def from_string(self, s):
3414 """Load value from a single string"""
3415 if not isinstance(s, str):
3416 raise TypeError(f"from_string expects a string, got {repr(s)} of type {type(s)}")
3417 try:
3418 return self.from_string_list([s])
3419 except Exception:
3420 test = _safe_literal_eval(s)
3421 if isinstance(test, dict):
3422 return test
3423 raise
3425 def from_string_list(self, s_list):
3426 """Return a dict from a list of config strings.
3428 This is where we parse CLI configuration.
3430 Each item should have the form ``"key=value"``.
3432 item parsing is done in :meth:`.item_from_string`.
3433 """
3434 if len(s_list) == 1 and s_list[0] == "None" and self.allow_none:
3435 return None
3436 if len(s_list) == 1 and s_list[0].startswith("{") and s_list[0].endswith("}"):
3437 warn(
3438 "--{0}={1} for dict-traits is deprecated in traitlets 5.0. "
3439 "You can pass --{0} <key=value> ... multiple times to add items to a dict.".format(
3440 self.name,
3441 s_list[0],
3442 ),
3443 FutureWarning,
3444 )
3446 return literal_eval(s_list[0])
3448 combined = {}
3449 for d in [self.item_from_string(s) for s in s_list]:
3450 combined.update(d)
3451 return combined
3453 def item_from_string(self, s):
3454 """Cast a single-key dict from a string.
3456 Evaluated when parsing CLI configuration from a string.
3458 Dicts expect strings of the form key=value.
3460 Returns a one-key dictionary,
3461 which will be merged in :meth:`.from_string_list`.
3462 """
3464 if "=" not in s:
3465 raise TraitError(
3466 "'%s' options must have the form 'key=value', got %s"
3467 % (
3468 self.__class__.__name__,
3469 repr(s),
3470 )
3471 )
3472 key, value = s.split("=", 1)
3474 # cast key with key trait, if defined
3475 if self._key_trait:
3476 key = self._key_trait.from_string(key)
3478 # cast value with value trait, if defined (per-key or global)
3479 value_trait = (self._per_key_traits or {}).get(key, self._value_trait)
3480 if value_trait:
3481 value = value_trait.from_string(value)
3482 return {key: value}
3485class TCPAddress(TraitType):
3486 """A trait for an (ip, port) tuple.
3488 This allows for both IPv4 IP addresses as well as hostnames.
3489 """
3491 default_value = ("127.0.0.1", 0)
3492 info_text = "an (ip, port) tuple"
3494 def validate(self, obj, value):
3495 if isinstance(value, tuple):
3496 if len(value) == 2:
3497 if isinstance(value[0], str) and isinstance(value[1], int):
3498 port = value[1]
3499 if port >= 0 and port <= 65535:
3500 return value
3501 self.error(obj, value)
3503 def from_string(self, s):
3504 if self.allow_none and s == "None":
3505 return None
3506 if ":" not in s:
3507 raise ValueError("Require `ip:port`, got %r" % s)
3508 ip, port = s.split(":", 1)
3509 port = int(port)
3510 return (ip, port)
3513class CRegExp(TraitType):
3514 """A casting compiled regular expression trait.
3516 Accepts both strings and compiled regular expressions. The resulting
3517 attribute will be a compiled regular expression."""
3519 info_text = "a regular expression"
3521 def validate(self, obj, value):
3522 try:
3523 return re.compile(value)
3524 except Exception:
3525 self.error(obj, value)
3528class UseEnum(TraitType):
3529 """Use a Enum class as model for the data type description.
3530 Note that if no default-value is provided, the first enum-value is used
3531 as default-value.
3533 .. sourcecode:: python
3535 # -- SINCE: Python 3.4 (or install backport: pip install enum34)
3536 import enum
3537 from traitlets import HasTraits, UseEnum
3539 class Color(enum.Enum):
3540 red = 1 # -- IMPLICIT: default_value
3541 blue = 2
3542 green = 3
3544 class MyEntity(HasTraits):
3545 color = UseEnum(Color, default_value=Color.blue)
3547 entity = MyEntity(color=Color.red)
3548 entity.color = Color.green # USE: Enum-value (preferred)
3549 entity.color = "green" # USE: name (as string)
3550 entity.color = "Color.green" # USE: scoped-name (as string)
3551 entity.color = 3 # USE: number (as int)
3552 assert entity.color is Color.green
3553 """
3555 default_value: t.Optional[enum.Enum] = None
3556 info_text = "Trait type adapter to a Enum class"
3558 def __init__(self, enum_class, default_value=None, **kwargs):
3559 assert issubclass(enum_class, enum.Enum), "REQUIRE: enum.Enum, but was: %r" % enum_class
3560 allow_none = kwargs.get("allow_none", False)
3561 if default_value is None and not allow_none:
3562 default_value = list(enum_class.__members__.values())[0]
3563 super().__init__(default_value=default_value, **kwargs)
3564 self.enum_class = enum_class
3565 self.name_prefix = enum_class.__name__ + "."
3567 def select_by_number(self, value, default=Undefined):
3568 """Selects enum-value by using its number-constant."""
3569 assert isinstance(value, int)
3570 enum_members = self.enum_class.__members__
3571 for enum_item in enum_members.values():
3572 if enum_item.value == value:
3573 return enum_item
3574 # -- NOT FOUND:
3575 return default
3577 def select_by_name(self, value, default=Undefined):
3578 """Selects enum-value by using its name or scoped-name."""
3579 assert isinstance(value, str)
3580 if value.startswith(self.name_prefix):
3581 # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
3582 value = value.replace(self.name_prefix, "", 1)
3583 return self.enum_class.__members__.get(value, default)
3585 def validate(self, obj, value):
3586 if isinstance(value, self.enum_class):
3587 return value
3588 elif isinstance(value, int):
3589 # -- CONVERT: number => enum_value (item)
3590 value2 = self.select_by_number(value)
3591 if value2 is not Undefined:
3592 return value2
3593 elif isinstance(value, str):
3594 # -- CONVERT: name or scoped_name (as string) => enum_value (item)
3595 value2 = self.select_by_name(value)
3596 if value2 is not Undefined:
3597 return value2
3598 elif value is None:
3599 if self.allow_none:
3600 return None
3601 else:
3602 return self.default_value
3603 self.error(obj, value)
3605 def _choices_str(self, as_rst=False):
3606 """Returns a description of the trait choices (not none)."""
3607 choices = self.enum_class.__members__.keys()
3608 if as_rst:
3609 return "|".join("``%r``" % x for x in choices)
3610 else:
3611 return repr(list(choices)) # Listify because py3.4- prints odict-class
3613 def _info(self, as_rst=False):
3614 """Returns a description of the trait."""
3615 none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else ""
3616 return f"any of {self._choices_str(as_rst)}{none}"
3618 def info(self):
3619 return self._info(as_rst=False)
3621 def info_rst(self):
3622 return self._info(as_rst=True)
3625class Callable(TraitType):
3626 """A trait which is callable.
3628 Notes
3629 -----
3630 Classes are callable, as are instances
3631 with a __call__() method."""
3633 info_text = "a callable"
3635 def validate(self, obj, value):
3636 if callable(value):
3637 return value
3638 else:
3639 self.error(obj, value)