You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2690 lines
93 KiB

4 years ago
  1. # encoding: utf-8
  2. """
  3. A lightweight Traits like module.
  4. This is designed to provide a lightweight, simple, pure Python version of
  5. many of the capabilities of enthought.traits. This includes:
  6. * Validation
  7. * Type specification with defaults
  8. * Static and dynamic notification
  9. * Basic predefined types
  10. * An API that is similar to enthought.traits
  11. We don't support:
  12. * Delegation
  13. * Automatic GUI generation
  14. * A full set of trait types. Most importantly, we don't provide container
  15. traits (list, dict, tuple) that can trigger notifications if their
  16. contents change.
  17. * API compatibility with enthought.traits
  18. There are also some important difference in our design:
  19. * enthought.traits does not validate default values. We do.
  20. We choose to create this module because we need these capabilities, but
  21. we need them to be pure Python so they work in all Python implementations,
  22. including Jython and IronPython.
  23. Inheritance diagram:
  24. .. inheritance-diagram:: traitlets.traitlets
  25. :parts: 3
  26. """
  27. # Copyright (c) IPython Development Team.
  28. # Distributed under the terms of the Modified BSD License.
  29. #
  30. # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
  31. # also under the terms of the Modified BSD License.
  32. import contextlib
  33. import inspect
  34. import os
  35. import re
  36. import sys
  37. import types
  38. import enum
  39. try:
  40. from types import ClassType, InstanceType
  41. ClassTypes = (ClassType, type)
  42. except:
  43. ClassTypes = (type,)
  44. from warnings import warn, warn_explicit
  45. import six
  46. from .utils.getargspec import getargspec
  47. from .utils.importstring import import_item
  48. from .utils.sentinel import Sentinel
  49. from .utils.bunch import Bunch
  50. SequenceTypes = (list, tuple, set, frozenset)
  51. #-----------------------------------------------------------------------------
  52. # Basic classes
  53. #-----------------------------------------------------------------------------
  54. Undefined = Sentinel('Undefined', 'traitlets',
  55. '''
  56. Used in Traitlets to specify that no defaults are set in kwargs
  57. '''
  58. )
  59. All = Sentinel('All', 'traitlets',
  60. '''
  61. Used in Traitlets to listen to all types of notification or to notifications
  62. from all trait attributes.
  63. '''
  64. )
  65. # Deprecated alias
  66. NoDefaultSpecified = Undefined
  67. class TraitError(Exception):
  68. pass
  69. #-----------------------------------------------------------------------------
  70. # Utilities
  71. #-----------------------------------------------------------------------------
  72. from ipython_genutils.py3compat import cast_unicode_py2
  73. _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
  74. def isidentifier(s):
  75. if six.PY2:
  76. return bool(_name_re.match(s))
  77. else:
  78. return s.isidentifier()
  79. _deprecations_shown = set()
  80. def _should_warn(key):
  81. """Add our own checks for too many deprecation warnings.
  82. Limit to once per package.
  83. """
  84. env_flag = os.environ.get('TRAITLETS_ALL_DEPRECATIONS')
  85. if env_flag and env_flag != '0':
  86. return True
  87. if key not in _deprecations_shown:
  88. _deprecations_shown.add(key)
  89. return True
  90. else:
  91. return False
  92. def _deprecated_method(method, cls, method_name, msg):
  93. """Show deprecation warning about a magic method definition.
  94. Uses warn_explicit to bind warning to method definition instead of triggering code,
  95. which isn't relevant.
  96. """
  97. warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format(
  98. classname=cls.__name__, method_name=method_name, msg=msg
  99. )
  100. for parent in inspect.getmro(cls):
  101. if method_name in parent.__dict__:
  102. cls = parent
  103. break
  104. # limit deprecation messages to once per package
  105. package_name = cls.__module__.split('.', 1)[0]
  106. key = (package_name, msg)
  107. if not _should_warn(key):
  108. return
  109. try:
  110. fname = inspect.getsourcefile(method) or "<unknown>"
  111. lineno = inspect.getsourcelines(method)[1] or 0
  112. except (IOError, TypeError) as e:
  113. # Failed to inspect for some reason
  114. warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning)
  115. else:
  116. warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
  117. def class_of(object):
  118. """ Returns a string containing the class name of an object with the
  119. correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
  120. 'a PlotValue').
  121. """
  122. if isinstance( object, six.string_types ):
  123. return add_article( object )
  124. return add_article( object.__class__.__name__ )
  125. def add_article(name):
  126. """ Returns a string containing the correct indefinite article ('a' or 'an')
  127. prefixed to the specified string.
  128. """
  129. if name[:1].lower() in 'aeiou':
  130. return 'an ' + name
  131. return 'a ' + name
  132. def repr_type(obj):
  133. """ Return a string representation of a value and its type for readable
  134. error messages.
  135. """
  136. the_type = type(obj)
  137. if six.PY2 and the_type is InstanceType:
  138. # Old-style class.
  139. the_type = obj.__class__
  140. msg = '%r %r' % (obj, the_type)
  141. return msg
  142. def is_trait(t):
  143. """ Returns whether the given value is an instance or subclass of TraitType.
  144. """
  145. return (isinstance(t, TraitType) or
  146. (isinstance(t, type) and issubclass(t, TraitType)))
  147. def parse_notifier_name(names):
  148. """Convert the name argument to a list of names.
  149. Examples
  150. --------
  151. >>> parse_notifier_name([])
  152. [All]
  153. >>> parse_notifier_name('a')
  154. ['a']
  155. >>> parse_notifier_name(['a', 'b'])
  156. ['a', 'b']
  157. >>> parse_notifier_name(All)
  158. [All]
  159. """
  160. if names is All or isinstance(names, six.string_types):
  161. return [names]
  162. else:
  163. if not names or All in names:
  164. return [All]
  165. for n in names:
  166. if not isinstance(n, six.string_types):
  167. raise TypeError("names must be strings, not %r" % n)
  168. return names
  169. class _SimpleTest:
  170. def __init__ ( self, value ): self.value = value
  171. def __call__ ( self, test ):
  172. return test == self.value
  173. def __repr__(self):
  174. return "<SimpleTest(%r)" % self.value
  175. def __str__(self):
  176. return self.__repr__()
  177. def getmembers(object, predicate=None):
  178. """A safe version of inspect.getmembers that handles missing attributes.
  179. This is useful when there are descriptor based attributes that for
  180. some reason raise AttributeError even though they exist. This happens
  181. in zope.inteface with the __provides__ attribute.
  182. """
  183. results = []
  184. for key in dir(object):
  185. try:
  186. value = getattr(object, key)
  187. except AttributeError:
  188. pass
  189. else:
  190. if not predicate or predicate(value):
  191. results.append((key, value))
  192. results.sort()
  193. return results
  194. def _validate_link(*tuples):
  195. """Validate arguments for traitlet link functions"""
  196. for t in tuples:
  197. if not len(t) == 2:
  198. raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
  199. obj, trait_name = t
  200. if not isinstance(obj, HasTraits):
  201. raise TypeError("Each object must be HasTraits, not %r" % type(obj))
  202. if not trait_name in obj.traits():
  203. raise TypeError("%r has no trait %r" % (obj, trait_name))
  204. class link(object):
  205. """Link traits from different objects together so they remain in sync.
  206. Parameters
  207. ----------
  208. source : (object / attribute name) pair
  209. target : (object / attribute name) pair
  210. Examples
  211. --------
  212. >>> c = link((src, 'value'), (tgt, 'value'))
  213. >>> src.value = 5 # updates other objects as well
  214. """
  215. updating = False
  216. def __init__(self, source, target):
  217. _validate_link(source, target)
  218. self.source, self.target = source, target
  219. try:
  220. setattr(target[0], target[1], getattr(source[0], source[1]))
  221. finally:
  222. source[0].observe(self._update_target, names=source[1])
  223. target[0].observe(self._update_source, names=target[1])
  224. @contextlib.contextmanager
  225. def _busy_updating(self):
  226. self.updating = True
  227. try:
  228. yield
  229. finally:
  230. self.updating = False
  231. def _update_target(self, change):
  232. if self.updating:
  233. return
  234. with self._busy_updating():
  235. setattr(self.target[0], self.target[1], change.new)
  236. def _update_source(self, change):
  237. if self.updating:
  238. return
  239. with self._busy_updating():
  240. setattr(self.source[0], self.source[1], change.new)
  241. def unlink(self):
  242. self.source[0].unobserve(self._update_target, names=self.source[1])
  243. self.target[0].unobserve(self._update_source, names=self.target[1])
  244. self.source, self.target = None, None
  245. class directional_link(object):
  246. """Link the trait of a source object with traits of target objects.
  247. Parameters
  248. ----------
  249. source : (object, attribute name) pair
  250. target : (object, attribute name) pair
  251. transform: callable (optional)
  252. Data transformation between source and target.
  253. Examples
  254. --------
  255. >>> c = directional_link((src, 'value'), (tgt, 'value'))
  256. >>> src.value = 5 # updates target objects
  257. >>> tgt.value = 6 # does not update source object
  258. """
  259. updating = False
  260. def __init__(self, source, target, transform=None):
  261. self._transform = transform if transform else lambda x: x
  262. _validate_link(source, target)
  263. self.source, self.target = source, target
  264. try:
  265. setattr(target[0], target[1],
  266. self._transform(getattr(source[0], source[1])))
  267. finally:
  268. self.source[0].observe(self._update, names=self.source[1])
  269. @contextlib.contextmanager
  270. def _busy_updating(self):
  271. self.updating = True
  272. try:
  273. yield
  274. finally:
  275. self.updating = False
  276. def _update(self, change):
  277. if self.updating:
  278. return
  279. with self._busy_updating():
  280. setattr(self.target[0], self.target[1],
  281. self._transform(change.new))
  282. def unlink(self):
  283. self.source[0].unobserve(self._update, names=self.source[1])
  284. self.source, self.target = None, None
  285. dlink = directional_link
  286. #-----------------------------------------------------------------------------
  287. # Base Descriptor Class
  288. #-----------------------------------------------------------------------------
  289. class BaseDescriptor(object):
  290. """Base descriptor class
  291. Notes
  292. -----
  293. This implements Python's descriptor prototol.
  294. This class is the base class for all such descriptors. The
  295. only magic we use is a custom metaclass for the main :class:`HasTraits`
  296. class that does the following:
  297. 1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
  298. instance in the class dict to the name of the attribute.
  299. 2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
  300. instance in the class dict to the *class* that declared the trait.
  301. This is used by the :class:`This` trait to allow subclasses to
  302. accept superclasses for :class:`This` values.
  303. """
  304. name = None
  305. this_class = None
  306. def class_init(self, cls, name):
  307. """Part of the initialization which may depend on the underlying
  308. HasDescriptors class.
  309. It is typically overloaded for specific types.
  310. This method is called by :meth:`MetaHasDescriptors.__init__`
  311. passing the class (`cls`) and `name` under which the descriptor
  312. has been assigned.
  313. """
  314. self.this_class = cls
  315. self.name = name
  316. def instance_init(self, obj):
  317. """Part of the initialization which may depend on the underlying
  318. HasDescriptors instance.
  319. It is typically overloaded for specific types.
  320. This method is called by :meth:`HasTraits.__new__` and in the
  321. :meth:`BaseDescriptor.instance_init` method of descriptors holding
  322. other descriptors.
  323. """
  324. pass
  325. class TraitType(BaseDescriptor):
  326. """A base class for all trait types.
  327. """
  328. metadata = {}
  329. default_value = Undefined
  330. allow_none = False
  331. read_only = False
  332. info_text = 'any value'
  333. def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None,
  334. config=None, **kwargs):
  335. """Declare a traitlet.
  336. If *allow_none* is True, None is a valid value in addition to any
  337. values that are normally valid. The default is up to the subclass.
  338. For most trait types, the default value for ``allow_none`` is False.
  339. Extra metadata can be associated with the traitlet using the .tag() convenience method
  340. or by using the traitlet instance's .metadata dictionary.
  341. """
  342. if default_value is not Undefined:
  343. self.default_value = default_value
  344. if allow_none:
  345. self.allow_none = allow_none
  346. if read_only is not None:
  347. self.read_only = read_only
  348. self.help = help if help is not None else ''
  349. if len(kwargs) > 0:
  350. stacklevel = 1
  351. f = inspect.currentframe()
  352. # count supers to determine stacklevel for warning
  353. while f.f_code.co_name == '__init__':
  354. stacklevel += 1
  355. f = f.f_back
  356. mod = f.f_globals.get('__name__') or ''
  357. pkg = mod.split('.', 1)[0]
  358. key = tuple(['metadata-tag', pkg] + sorted(kwargs))
  359. if _should_warn(key):
  360. warn("metadata %s was set from the constructor. "
  361. "With traitlets 4.1, metadata should be set using the .tag() method, "
  362. "e.g., Int().tag(key1='value1', key2='value2')" % (kwargs,),
  363. DeprecationWarning, stacklevel=stacklevel)
  364. if len(self.metadata) > 0:
  365. self.metadata = self.metadata.copy()
  366. self.metadata.update(kwargs)
  367. else:
  368. self.metadata = kwargs
  369. else:
  370. self.metadata = self.metadata.copy()
  371. if config is not None:
  372. self.metadata['config'] = config
  373. # We add help to the metadata during a deprecation period so that
  374. # code that looks for the help string there can find it.
  375. if help is not None:
  376. self.metadata['help'] = help
  377. def get_default_value(self):
  378. """DEPRECATED: Retrieve the static default value for this trait.
  379. Use self.default_value instead
  380. """
  381. warn("get_default_value is deprecated in traitlets 4.0: use the .default_value attribute", DeprecationWarning,
  382. stacklevel=2)
  383. return self.default_value
  384. def init_default_value(self, obj):
  385. """DEPRECATED: Set the static default value for the trait type.
  386. """
  387. warn("init_default_value is deprecated in traitlets 4.0, and may be removed in the future", DeprecationWarning,
  388. stacklevel=2)
  389. value = self._validate(obj, self.default_value)
  390. obj._trait_values[self.name] = value
  391. return value
  392. def _dynamic_default_callable(self, obj):
  393. """Retrieve a callable to calculate the default for this traitlet.
  394. This looks for:
  395. * default generators registered with the @default descriptor.
  396. * obj._{name}_default() on the class with the traitlet, or a subclass
  397. that obj belongs to.
  398. * trait.make_dynamic_default, which is defined by Instance
  399. If neither exist, it returns None
  400. """
  401. # Traitlets without a name are not on the instance, e.g. in List or Union
  402. if self.name:
  403. # Only look for default handlers in classes derived from self.this_class.
  404. mro = type(obj).mro()
  405. meth_name = '_%s_default' % self.name
  406. for cls in mro[:mro.index(self.this_class) + 1]:
  407. if hasattr(cls, '_trait_default_generators'):
  408. default_handler = cls._trait_default_generators.get(self.name)
  409. if default_handler is not None and default_handler.this_class == cls:
  410. return types.MethodType(default_handler.func, obj)
  411. if meth_name in cls.__dict__:
  412. method = getattr(obj, meth_name)
  413. return method
  414. return getattr(self, 'make_dynamic_default', None)
  415. def instance_init(self, obj):
  416. # If no dynamic initialiser is present, and the trait implementation or
  417. # use provides a static default, transfer that to obj._trait_values.
  418. with obj.cross_validation_lock:
  419. if (self._dynamic_default_callable(obj) is None) \
  420. and (self.default_value is not Undefined):
  421. v = self._validate(obj, self.default_value)
  422. if self.name is not None:
  423. obj._trait_values[self.name] = v
  424. def get(self, obj, cls=None):
  425. try:
  426. value = obj._trait_values[self.name]
  427. except KeyError:
  428. # Check for a dynamic initializer.
  429. dynamic_default = self._dynamic_default_callable(obj)
  430. if dynamic_default is None:
  431. raise TraitError("No default value found for %s trait of %r"
  432. % (self.name, obj))
  433. value = self._validate(obj, dynamic_default())
  434. obj._trait_values[self.name] = value
  435. return value
  436. except Exception:
  437. # This should never be reached.
  438. raise TraitError('Unexpected error in TraitType: '
  439. 'default value not set properly')
  440. else:
  441. return value
  442. def __get__(self, obj, cls=None):
  443. """Get the value of the trait by self.name for the instance.
  444. Default values are instantiated when :meth:`HasTraits.__new__`
  445. is called. Thus by the time this method gets called either the
  446. default value or a user defined value (they called :meth:`__set__`)
  447. is in the :class:`HasTraits` instance.
  448. """
  449. if obj is None:
  450. return self
  451. else:
  452. return self.get(obj, cls)
  453. def set(self, obj, value):
  454. new_value = self._validate(obj, value)
  455. try:
  456. old_value = obj._trait_values[self.name]
  457. except KeyError:
  458. old_value = self.default_value
  459. obj._trait_values[self.name] = new_value
  460. try:
  461. silent = bool(old_value == new_value)
  462. except:
  463. # if there is an error in comparing, default to notify
  464. silent = False
  465. if silent is not True:
  466. # we explicitly compare silent to True just in case the equality
  467. # comparison above returns something other than True/False
  468. obj._notify_trait(self.name, old_value, new_value)
  469. def __set__(self, obj, value):
  470. """Set the value of the trait by self.name for the instance.
  471. Values pass through a validation stage where errors are raised when
  472. impropper types, or types that cannot be coerced, are encountered.
  473. """
  474. if self.read_only:
  475. raise TraitError('The "%s" trait is read-only.' % self.name)
  476. else:
  477. self.set(obj, value)
  478. def _validate(self, obj, value):
  479. if value is None and self.allow_none:
  480. return value
  481. if hasattr(self, 'validate'):
  482. value = self.validate(obj, value)
  483. if obj._cross_validation_lock is False:
  484. value = self._cross_validate(obj, value)
  485. return value
  486. def _cross_validate(self, obj, value):
  487. if self.name in obj._trait_validators:
  488. proposal = Bunch({'trait': self, 'value': value, 'owner': obj})
  489. value = obj._trait_validators[self.name](obj, proposal)
  490. elif hasattr(obj, '_%s_validate' % self.name):
  491. meth_name = '_%s_validate' % self.name
  492. cross_validate = getattr(obj, meth_name)
  493. _deprecated_method(cross_validate, obj.__class__, meth_name,
  494. "use @validate decorator instead.")
  495. value = cross_validate(value, self)
  496. return value
  497. def __or__(self, other):
  498. if isinstance(other, Union):
  499. return Union([self] + other.trait_types)
  500. else:
  501. return Union([self, other])
  502. def info(self):
  503. return self.info_text
  504. def error(self, obj, value):
  505. if obj is not None:
  506. e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
  507. % (self.name, class_of(obj),
  508. self.info(), repr_type(value))
  509. else:
  510. e = "The '%s' trait must be %s, but a value of %r was specified." \
  511. % (self.name, self.info(), repr_type(value))
  512. raise TraitError(e)
  513. def get_metadata(self, key, default=None):
  514. """DEPRECATED: Get a metadata value.
  515. Use .metadata[key] or .metadata.get(key, default) instead.
  516. """
  517. if key == 'help':
  518. msg = "use the instance .help string directly, like x.help"
  519. else:
  520. msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
  521. warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
  522. return self.metadata.get(key, default)
  523. def set_metadata(self, key, value):
  524. """DEPRECATED: Set a metadata key/value.
  525. Use .metadata[key] = value instead.
  526. """
  527. if key == 'help':
  528. msg = "use the instance .help string directly, like x.help = value"
  529. else:
  530. msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value"
  531. warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
  532. self.metadata[key] = value
  533. def tag(self, **metadata):
  534. """Sets metadata and returns self.
  535. This allows convenient metadata tagging when initializing the trait, such as:
  536. >>> Int(0).tag(config=True, sync=True)
  537. """
  538. maybe_constructor_keywords = set(metadata.keys()).intersection({'help','allow_none', 'read_only', 'default_value'})
  539. if maybe_constructor_keywords:
  540. warn('The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s '%
  541. maybe_constructor_keywords, UserWarning, stacklevel=2)
  542. self.metadata.update(metadata)
  543. return self
  544. def default_value_repr(self):
  545. return repr(self.default_value)
  546. #-----------------------------------------------------------------------------
  547. # The HasTraits implementation
  548. #-----------------------------------------------------------------------------
  549. class _CallbackWrapper(object):
  550. """An object adapting a on_trait_change callback into an observe callback.
  551. The comparison operator __eq__ is implemented to enable removal of wrapped
  552. callbacks.
  553. """
  554. def __init__(self, cb):
  555. self.cb = cb
  556. # Bound methods have an additional 'self' argument.
  557. offset = -1 if isinstance(self.cb, types.MethodType) else 0
  558. self.nargs = len(getargspec(cb)[0]) + offset
  559. if (self.nargs > 4):
  560. raise TraitError('a trait changed callback must have 0-4 arguments.')
  561. def __eq__(self, other):
  562. # The wrapper is equal to the wrapped element
  563. if isinstance(other, _CallbackWrapper):
  564. return self.cb == other.cb
  565. else:
  566. return self.cb == other
  567. def __call__(self, change):
  568. # The wrapper is callable
  569. if self.nargs == 0:
  570. self.cb()
  571. elif self.nargs == 1:
  572. self.cb(change.name)
  573. elif self.nargs == 2:
  574. self.cb(change.name, change.new)
  575. elif self.nargs == 3:
  576. self.cb(change.name, change.old, change.new)
  577. elif self.nargs == 4:
  578. self.cb(change.name, change.old, change.new, change.owner)
  579. def _callback_wrapper(cb):
  580. if isinstance(cb, _CallbackWrapper):
  581. return cb
  582. else:
  583. return _CallbackWrapper(cb)
  584. class MetaHasDescriptors(type):
  585. """A metaclass for HasDescriptors.
  586. This metaclass makes sure that any TraitType class attributes are
  587. instantiated and sets their name attribute.
  588. """
  589. def __new__(mcls, name, bases, classdict):
  590. """Create the HasDescriptors class."""
  591. for k, v in classdict.items():
  592. # ----------------------------------------------------------------
  593. # Support of deprecated behavior allowing for TraitType types
  594. # to be used instead of TraitType instances.
  595. if inspect.isclass(v) and issubclass(v, TraitType):
  596. warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
  597. " Passing types is deprecated in traitlets 4.1.",
  598. DeprecationWarning, stacklevel=2)
  599. classdict[k] = v()
  600. # ----------------------------------------------------------------
  601. return super(MetaHasDescriptors, mcls).__new__(mcls, name, bases, classdict)
  602. def __init__(cls, name, bases, classdict):
  603. """Finish initializing the HasDescriptors class."""
  604. super(MetaHasDescriptors, cls).__init__(name, bases, classdict)
  605. cls.setup_class(classdict)
  606. def setup_class(cls, classdict):
  607. """Setup descriptor instance on the class
  608. This sets the :attr:`this_class` and :attr:`name` attributes of each
  609. BaseDescriptor in the class dict of the newly created ``cls`` before
  610. calling their :attr:`class_init` method.
  611. """
  612. for k, v in classdict.items():
  613. if isinstance(v, BaseDescriptor):
  614. v.class_init(cls, k)
  615. class MetaHasTraits(MetaHasDescriptors):
  616. """A metaclass for HasTraits."""
  617. def setup_class(cls, classdict):
  618. cls._trait_default_generators = {}
  619. super(MetaHasTraits, cls).setup_class(classdict)
  620. def observe(*names, **kwargs):
  621. """A decorator which can be used to observe Traits on a class.
  622. The handler passed to the decorator will be called with one ``change``
  623. dict argument. The change dictionary at least holds a 'type' key and a
  624. 'name' key, corresponding respectively to the type of notification and the
  625. name of the attribute that triggered the notification.
  626. Other keys may be passed depending on the value of 'type'. In the case
  627. where type is 'change', we also have the following keys:
  628. * ``owner`` : the HasTraits instance
  629. * ``old`` : the old value of the modified trait attribute
  630. * ``new`` : the new value of the modified trait attribute
  631. * ``name`` : the name of the modified trait attribute.
  632. Parameters
  633. ----------
  634. *names
  635. The str names of the Traits to observe on the object.
  636. type: str, kwarg-only
  637. The type of event to observe (e.g. 'change')
  638. """
  639. if not names:
  640. raise TypeError("Please specify at least one trait name to observe.")
  641. for name in names:
  642. if name is not All and not isinstance(name, six.string_types):
  643. raise TypeError("trait names to observe must be strings or All, not %r" % name)
  644. return ObserveHandler(names, type=kwargs.get('type', 'change'))
  645. def observe_compat(func):
  646. """Backward-compatibility shim decorator for observers
  647. Use with:
  648. @observe('name')
  649. @observe_compat
  650. def _foo_changed(self, change):
  651. ...
  652. With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
  653. Allows adoption of new observer API without breaking subclasses that override and super.
  654. """
  655. def compatible_observer(self, change_or_name, old=Undefined, new=Undefined):
  656. if isinstance(change_or_name, dict):
  657. change = change_or_name
  658. else:
  659. clsname = self.__class__.__name__
  660. warn("A parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) API" % (
  661. clsname, change_or_name), DeprecationWarning)
  662. change = Bunch(
  663. type='change',
  664. old=old,
  665. new=new,
  666. name=change_or_name,
  667. owner=self,
  668. )
  669. return func(self, change)
  670. return compatible_observer
  671. def validate(*names):
  672. """A decorator to register cross validator of HasTraits object's state
  673. when a Trait is set.
  674. The handler passed to the decorator must have one ``proposal`` dict argument.
  675. The proposal dictionary must hold the following keys:
  676. * ``owner`` : the HasTraits instance
  677. * ``value`` : the proposed value for the modified trait attribute
  678. * ``trait`` : the TraitType instance associated with the attribute
  679. Parameters
  680. ----------
  681. names
  682. The str names of the Traits to validate.
  683. Notes
  684. -----
  685. Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
  686. the registered cross validator could potentially make changes to attributes
  687. of the ``HasTraits`` instance. However, we recommend not to do so. The reason
  688. is that the cross-validation of attributes may run in arbitrary order when
  689. exiting the ``hold_trait_notifications`` context, and such changes may not
  690. commute.
  691. """
  692. if not names:
  693. raise TypeError("Please specify at least one trait name to validate.")
  694. for name in names:
  695. if name is not All and not isinstance(name, six.string_types):
  696. raise TypeError("trait names to validate must be strings or All, not %r" % name)
  697. return ValidateHandler(names)
  698. def default(name):
  699. """ A decorator which assigns a dynamic default for a Trait on a HasTraits object.
  700. Parameters
  701. ----------
  702. name
  703. The str name of the Trait on the object whose default should be generated.
  704. Notes
  705. -----
  706. Unlike observers and validators which are properties of the HasTraits
  707. instance, default value generators are class-level properties.
  708. Besides, default generators are only invoked if they are registered in
  709. subclasses of `this_type`.
  710. ::
  711. class A(HasTraits):
  712. bar = Int()
  713. @default('bar')
  714. def get_bar_default(self):
  715. return 11
  716. class B(A):
  717. bar = Float() # This trait ignores the default generator defined in
  718. # the base class A
  719. class C(B):
  720. @default('bar')
  721. def some_other_default(self): # This default generator should not be
  722. return 3.0 # ignored since it is defined in a
  723. # class derived from B.a.this_class.
  724. """
  725. if not isinstance(name, six.string_types):
  726. raise TypeError("Trait name must be a string or All, not %r" % name)
  727. return DefaultHandler(name)
  728. class EventHandler(BaseDescriptor):
  729. def _init_call(self, func):
  730. self.func = func
  731. return self
  732. def __call__(self, *args, **kwargs):
  733. """Pass `*args` and `**kwargs` to the handler's function if it exists."""
  734. if hasattr(self, 'func'):
  735. return self.func(*args, **kwargs)
  736. else:
  737. return self._init_call(*args, **kwargs)
  738. def __get__(self, inst, cls=None):
  739. if inst is None:
  740. return self
  741. return types.MethodType(self.func, inst)
  742. class ObserveHandler(EventHandler):
  743. def __init__(self, names, type):
  744. self.trait_names = names
  745. self.type = type
  746. def instance_init(self, inst):
  747. inst.observe(self, self.trait_names, type=self.type)
  748. class ValidateHandler(EventHandler):
  749. def __init__(self, names):
  750. self.trait_names = names
  751. def instance_init(self, inst):
  752. inst._register_validator(self, self.trait_names)
  753. class DefaultHandler(EventHandler):
  754. def __init__(self, name):
  755. self.trait_name = name
  756. def class_init(self, cls, name):
  757. super(DefaultHandler, self).class_init(cls, name)
  758. cls._trait_default_generators[self.trait_name] = self
  759. class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
  760. """The base class for all classes that have descriptors.
  761. """
  762. def __new__(cls, *args, **kwargs):
  763. # This is needed because object.__new__ only accepts
  764. # the cls argument.
  765. new_meth = super(HasDescriptors, cls).__new__
  766. if new_meth is object.__new__:
  767. inst = new_meth(cls)
  768. else:
  769. inst = new_meth(cls, *args, **kwargs)
  770. inst.setup_instance(*args, **kwargs)
  771. return inst
  772. def setup_instance(self, *args, **kwargs):
  773. """
  774. This is called **before** self.__init__ is called.
  775. """
  776. self._cross_validation_lock = False
  777. cls = self.__class__
  778. for key in dir(cls):
  779. # Some descriptors raise AttributeError like zope.interface's
  780. # __provides__ attributes even though they exist. This causes
  781. # AttributeErrors even though they are listed in dir(cls).
  782. try:
  783. value = getattr(cls, key)
  784. except AttributeError:
  785. pass
  786. else:
  787. if isinstance(value, BaseDescriptor):
  788. value.instance_init(self)
  789. class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
  790. def setup_instance(self, *args, **kwargs):
  791. self._trait_values = {}
  792. self._trait_notifiers = {}
  793. self._trait_validators = {}
  794. super(HasTraits, self).setup_instance(*args, **kwargs)
  795. def __init__(self, *args, **kwargs):
  796. # Allow trait values to be set using keyword arguments.
  797. # We need to use setattr for this to trigger validation and
  798. # notifications.
  799. super_args = args
  800. super_kwargs = {}
  801. with self.hold_trait_notifications():
  802. for key, value in kwargs.items():
  803. if self.has_trait(key):
  804. setattr(self, key, value)
  805. else:
  806. # passthrough args that don't set traits to super
  807. super_kwargs[key] = value
  808. try:
  809. super(HasTraits, self).__init__(*super_args, **super_kwargs)
  810. except TypeError as e:
  811. arg_s_list = [ repr(arg) for arg in super_args ]
  812. for k, v in super_kwargs.items():
  813. arg_s_list.append("%s=%r" % (k, v))
  814. arg_s = ', '.join(arg_s_list)
  815. warn(
  816. "Passing unrecoginized arguments to super({classname}).__init__({arg_s}).\n"
  817. "{error}\n"
  818. "This is deprecated in traitlets 4.2."
  819. "This error will be raised in a future release of traitlets."
  820. .format(
  821. arg_s=arg_s, classname=self.__class__.__name__,
  822. error=e,
  823. ),
  824. DeprecationWarning,
  825. stacklevel=2,
  826. )
  827. def __getstate__(self):
  828. d = self.__dict__.copy()
  829. # event handlers stored on an instance are
  830. # expected to be reinstantiated during a
  831. # recall of instance_init during __setstate__
  832. d['_trait_notifiers'] = {}
  833. d['_trait_validators'] = {}
  834. return d
  835. def __setstate__(self, state):
  836. self.__dict__ = state.copy()
  837. # event handlers are reassigned to self
  838. cls = self.__class__
  839. for key in dir(cls):
  840. # Some descriptors raise AttributeError like zope.interface's
  841. # __provides__ attributes even though they exist. This causes
  842. # AttributeErrors even though they are listed in dir(cls).
  843. try:
  844. value = getattr(cls, key)
  845. except AttributeError:
  846. pass
  847. else:
  848. if isinstance(value, EventHandler):
  849. value.instance_init(self)
  850. @property
  851. @contextlib.contextmanager
  852. def cross_validation_lock(self):
  853. """
  854. A contextmanager for running a block with our cross validation lock set
  855. to True.
  856. At the end of the block, the lock's value is restored to its value
  857. prior to entering the block.
  858. """
  859. if self._cross_validation_lock:
  860. yield
  861. return
  862. else:
  863. try:
  864. self._cross_validation_lock = True
  865. yield
  866. finally:
  867. self._cross_validation_lock = False
  868. @contextlib.contextmanager
  869. def hold_trait_notifications(self):
  870. """Context manager for bundling trait change notifications and cross
  871. validation.
  872. Use this when doing multiple trait assignments (init, config), to avoid
  873. race conditions in trait notifiers requesting other trait values.
  874. All trait notifications will fire after all values have been assigned.
  875. """
  876. if self._cross_validation_lock:
  877. yield
  878. return
  879. else:
  880. cache = {}
  881. notify_change = self.notify_change
  882. def compress(past_changes, change):
  883. """Merges the provided change with the last if possible."""
  884. if past_changes is None:
  885. return [change]
  886. else:
  887. if past_changes[-1]['type'] == 'change' and change.type == 'change':
  888. past_changes[-1]['new'] = change.new
  889. else:
  890. # In case of changes other than 'change', append the notification.
  891. past_changes.append(change)
  892. return past_changes
  893. def hold(change):
  894. name = change.name
  895. cache[name] = compress(cache.get(name), change)
  896. try:
  897. # Replace notify_change with `hold`, caching and compressing
  898. # notifications, disable cross validation and yield.
  899. self.notify_change = hold
  900. self._cross_validation_lock = True
  901. yield
  902. # Cross validate final values when context is released.
  903. for name in list(cache.keys()):
  904. trait = getattr(self.__class__, name)
  905. value = trait._cross_validate(self, getattr(self, name))
  906. self.set_trait(name, value)
  907. except TraitError as e:
  908. # Roll back in case of TraitError during final cross validation.
  909. self.notify_change = lambda x: None
  910. for name, changes in cache.items():
  911. for change in changes[::-1]:
  912. # TODO: Separate in a rollback function per notification type.
  913. if change.type == 'change':
  914. if change.old is not Undefined:
  915. self.set_trait(name, change.old)
  916. else:
  917. self._trait_values.pop(name)
  918. cache = {}
  919. raise e
  920. finally:
  921. self._cross_validation_lock = False
  922. # Restore method retrieval from class
  923. del self.notify_change
  924. # trigger delayed notifications
  925. for changes in cache.values():
  926. for change in changes:
  927. self.notify_change(change)
  928. def _notify_trait(self, name, old_value, new_value):
  929. self.notify_change(Bunch(
  930. name=name,
  931. old=old_value,
  932. new=new_value,
  933. owner=self,
  934. type='change',
  935. ))
  936. def notify_change(self, change):
  937. if not isinstance(change, Bunch):
  938. # cast to bunch if given a dict
  939. change = Bunch(change)
  940. name, type = change.name, change.type
  941. callables = []
  942. callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
  943. callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
  944. callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
  945. callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
  946. # Now static ones
  947. magic_name = '_%s_changed' % name
  948. if hasattr(self, magic_name):
  949. class_value = getattr(self.__class__, magic_name)
  950. if not isinstance(class_value, ObserveHandler):
  951. _deprecated_method(class_value, self.__class__, magic_name,
  952. "use @observe and @unobserve instead.")
  953. cb = getattr(self, magic_name)
  954. # Only append the magic method if it was not manually registered
  955. if cb not in callables:
  956. callables.append(_callback_wrapper(cb))
  957. # Call them all now
  958. # Traits catches and logs errors here. I allow them to raise
  959. for c in callables:
  960. # Bound methods have an additional 'self' argument.
  961. if isinstance(c, _CallbackWrapper):
  962. c = c.__call__
  963. elif isinstance(c, EventHandler) and c.name is not None:
  964. c = getattr(self, c.name)
  965. c(change)
  966. def _add_notifiers(self, handler, name, type):
  967. if name not in self._trait_notifiers:
  968. nlist = []
  969. self._trait_notifiers[name] = {type: nlist}
  970. else:
  971. if type not in self._trait_notifiers[name]:
  972. nlist = []
  973. self._trait_notifiers[name][type] = nlist
  974. else:
  975. nlist = self._trait_notifiers[name][type]
  976. if handler not in nlist:
  977. nlist.append(handler)
  978. def _remove_notifiers(self, handler, name, type):
  979. try:
  980. if handler is None:
  981. del self._trait_notifiers[name][type]
  982. else:
  983. self._trait_notifiers[name][type].remove(handler)
  984. except KeyError:
  985. pass
  986. def on_trait_change(self, handler=None, name=None, remove=False):
  987. """DEPRECATED: Setup a handler to be called when a trait changes.
  988. This is used to setup dynamic notifications of trait changes.
  989. Static handlers can be created by creating methods on a HasTraits
  990. subclass with the naming convention '_[traitname]_changed'. Thus,
  991. to create static handler for the trait 'a', create the method
  992. _a_changed(self, name, old, new) (fewer arguments can be used, see
  993. below).
  994. If `remove` is True and `handler` is not specified, all change
  995. handlers for the specified name are uninstalled.
  996. Parameters
  997. ----------
  998. handler : callable, None
  999. A callable that is called when a trait changes. Its
  1000. signature can be handler(), handler(name), handler(name, new),
  1001. handler(name, old, new), or handler(name, old, new, self).
  1002. name : list, str, None
  1003. If None, the handler will apply to all traits. If a list
  1004. of str, handler will apply to all names in the list. If a
  1005. str, the handler will apply just to that name.
  1006. remove : bool
  1007. If False (the default), then install the handler. If True
  1008. then unintall it.
  1009. """
  1010. warn("on_trait_change is deprecated in traitlets 4.1: use observe instead",
  1011. DeprecationWarning, stacklevel=2)
  1012. if name is None:
  1013. name = All
  1014. if remove:
  1015. self.unobserve(_callback_wrapper(handler), names=name)
  1016. else:
  1017. self.observe(_callback_wrapper(handler), names=name)
  1018. def observe(self, handler, names=All, type='change'):
  1019. """Setup a handler to be called when a trait changes.
  1020. This is used to setup dynamic notifications of trait changes.
  1021. Parameters
  1022. ----------
  1023. handler : callable
  1024. A callable that is called when a trait changes. Its
  1025. signature should be ``handler(change)``, where ``change`` is a
  1026. dictionary. The change dictionary at least holds a 'type' key.
  1027. * ``type``: the type of notification.
  1028. Other keys may be passed depending on the value of 'type'. In the
  1029. case where type is 'change', we also have the following keys:
  1030. * ``owner`` : the HasTraits instance
  1031. * ``old`` : the old value of the modified trait attribute
  1032. * ``new`` : the new value of the modified trait attribute
  1033. * ``name`` : the name of the modified trait attribute.
  1034. names : list, str, All
  1035. If names is All, the handler will apply to all traits. If a list
  1036. of str, handler will apply to all names in the list. If a
  1037. str, the handler will apply just to that name.
  1038. type : str, All (default: 'change')
  1039. The type of notification to filter by. If equal to All, then all
  1040. notifications are passed to the observe handler.
  1041. """
  1042. names = parse_notifier_name(names)
  1043. for n in names:
  1044. self._add_notifiers(handler, n, type)
  1045. def unobserve(self, handler, names=All, type='change'):
  1046. """Remove a trait change handler.
  1047. This is used to unregister handlers to trait change notifications.
  1048. Parameters
  1049. ----------
  1050. handler : callable
  1051. The callable called when a trait attribute changes.
  1052. names : list, str, All (default: All)
  1053. The names of the traits for which the specified handler should be
  1054. uninstalled. If names is All, the specified handler is uninstalled
  1055. from the list of notifiers corresponding to all changes.
  1056. type : str or All (default: 'change')
  1057. The type of notification to filter by. If All, the specified handler
  1058. is uninstalled from the list of notifiers corresponding to all types.
  1059. """
  1060. names = parse_notifier_name(names)
  1061. for n in names:
  1062. self._remove_notifiers(handler, n, type)
  1063. def unobserve_all(self, name=All):
  1064. """Remove trait change handlers of any type for the specified name.
  1065. If name is not specified, removes all trait notifiers."""
  1066. if name is All:
  1067. self._trait_notifiers = {}
  1068. else:
  1069. try:
  1070. del self._trait_notifiers[name]
  1071. except KeyError:
  1072. pass
  1073. def _register_validator(self, handler, names):
  1074. """Setup a handler to be called when a trait should be cross validated.
  1075. This is used to setup dynamic notifications for cross-validation.
  1076. If a validator is already registered for any of the provided names, a
  1077. TraitError is raised and no new validator is registered.
  1078. Parameters
  1079. ----------
  1080. handler : callable
  1081. A callable that is called when the given trait is cross-validated.
  1082. Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
  1083. with the following attributes/keys:
  1084. * ``owner`` : the HasTraits instance
  1085. * ``value`` : the proposed value for the modified trait attribute
  1086. * ``trait`` : the TraitType instance associated with the attribute
  1087. names : List of strings
  1088. The names of the traits that should be cross-validated
  1089. """
  1090. for name in names:
  1091. magic_name = '_%s_validate' % name
  1092. if hasattr(self, magic_name):
  1093. class_value = getattr(self.__class__, magic_name)
  1094. if not isinstance(class_value, ValidateHandler):
  1095. _deprecated_method(class_value, self.__class, magic_name,
  1096. "use @validate decorator instead.")
  1097. for name in names:
  1098. self._trait_validators[name] = handler
  1099. def add_traits(self, **traits):
  1100. """Dynamically add trait attributes to the HasTraits instance."""
  1101. self.__class__ = type(self.__class__.__name__, (self.__class__,),
  1102. traits)
  1103. for trait in traits.values():
  1104. trait.instance_init(self)
  1105. def set_trait(self, name, value):
  1106. """Forcibly sets trait attribute, including read-only attributes."""
  1107. cls = self.__class__
  1108. if not self.has_trait(name):
  1109. raise TraitError("Class %s does not have a trait named %s" %
  1110. (cls.__name__, name))
  1111. else:
  1112. getattr(cls, name).set(self, value)
  1113. @classmethod
  1114. def class_trait_names(cls, **metadata):
  1115. """Get a list of all the names of this class' traits.
  1116. This method is just like the :meth:`trait_names` method,
  1117. but is unbound.
  1118. """
  1119. return list(cls.class_traits(**metadata))
  1120. @classmethod
  1121. def class_traits(cls, **metadata):
  1122. """Get a ``dict`` of all the traits of this class. The dictionary
  1123. is keyed on the name and the values are the TraitType objects.
  1124. This method is just like the :meth:`traits` method, but is unbound.
  1125. The TraitTypes returned don't know anything about the values
  1126. that the various HasTrait's instances are holding.
  1127. The metadata kwargs allow functions to be passed in which
  1128. filter traits based on metadata values. The functions should
  1129. take a single value as an argument and return a boolean. If
  1130. any function returns False, then the trait is not included in
  1131. the output. If a metadata key doesn't exist, None will be passed
  1132. to the function.
  1133. """
  1134. traits = dict([memb for memb in getmembers(cls) if
  1135. isinstance(memb[1], TraitType)])
  1136. if len(metadata) == 0:
  1137. return traits
  1138. result = {}
  1139. for name, trait in traits.items():
  1140. for meta_name, meta_eval in metadata.items():
  1141. if type(meta_eval) is not types.FunctionType:
  1142. meta_eval = _SimpleTest(meta_eval)
  1143. if not meta_eval(trait.metadata.get(meta_name, None)):
  1144. break
  1145. else:
  1146. result[name] = trait
  1147. return result
  1148. @classmethod
  1149. def class_own_traits(cls, **metadata):
  1150. """Get a dict of all the traitlets defined on this class, not a parent.
  1151. Works like `class_traits`, except for excluding traits from parents.
  1152. """
  1153. sup = super(cls, cls)
  1154. return {n: t for (n, t) in cls.class_traits(**metadata).items()
  1155. if getattr(sup, n, None) is not t}
  1156. def has_trait(self, name):
  1157. """Returns True if the object has a trait with the specified name."""
  1158. return isinstance(getattr(self.__class__, name, None), TraitType)
  1159. def trait_names(self, **metadata):
  1160. """Get a list of all the names of this class' traits."""
  1161. return list(self.traits(**metadata))
  1162. def traits(self, **metadata):
  1163. """Get a ``dict`` of all the traits of this class. The dictionary
  1164. is keyed on the name and the values are the TraitType objects.
  1165. The TraitTypes returned don't know anything about the values
  1166. that the various HasTrait's instances are holding.
  1167. The metadata kwargs allow functions to be passed in which
  1168. filter traits based on metadata values. The functions should
  1169. take a single value as an argument and return a boolean. If
  1170. any function returns False, then the trait is not included in
  1171. the output. If a metadata key doesn't exist, None will be passed
  1172. to the function.
  1173. """
  1174. traits = dict([memb for memb in getmembers(self.__class__) if
  1175. isinstance(memb[1], TraitType)])
  1176. if len(metadata) == 0:
  1177. return traits
  1178. result = {}
  1179. for name, trait in traits.items():
  1180. for meta_name, meta_eval in metadata.items():
  1181. if type(meta_eval) is not types.FunctionType:
  1182. meta_eval = _SimpleTest(meta_eval)
  1183. if not meta_eval(trait.metadata.get(meta_name, None)):
  1184. break
  1185. else:
  1186. result[name] = trait
  1187. return result
  1188. def trait_metadata(self, traitname, key, default=None):
  1189. """Get metadata values for trait by key."""
  1190. try:
  1191. trait = getattr(self.__class__, traitname)
  1192. except AttributeError:
  1193. raise TraitError("Class %s does not have a trait named %s" %
  1194. (self.__class__.__name__, traitname))
  1195. metadata_name = '_' + traitname + '_metadata'
  1196. if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
  1197. return getattr(self, metadata_name).get(key, default)
  1198. else:
  1199. return trait.metadata.get(key, default)
  1200. @classmethod
  1201. def class_own_trait_events(cls, name):
  1202. """Get a dict of all event handlers defined on this class, not a parent.
  1203. Works like ``event_handlers``, except for excluding traits from parents.
  1204. """
  1205. sup = super(cls, cls)
  1206. return {n: e for (n, e) in cls.events(name).items()
  1207. if getattr(sup, n, None) is not e}
  1208. @classmethod
  1209. def trait_events(cls, name=None):
  1210. """Get a ``dict`` of all the event handlers of this class.
  1211. Parameters
  1212. ----------
  1213. name: str (default: None)
  1214. The name of a trait of this class. If name is ``None`` then all
  1215. the event handlers of this class will be returned instead.
  1216. Returns
  1217. -------
  1218. The event handlers associated with a trait name, or all event handlers.
  1219. """
  1220. events = {}
  1221. for k, v in getmembers(cls):
  1222. if isinstance(v, EventHandler):
  1223. if name is None:
  1224. events[k] = v
  1225. elif name in v.trait_names:
  1226. events[k] = v
  1227. elif hasattr(v, 'tags'):
  1228. if cls.trait_names(**v.tags):
  1229. events[k] = v
  1230. return events
  1231. #-----------------------------------------------------------------------------
  1232. # Actual TraitTypes implementations/subclasses
  1233. #-----------------------------------------------------------------------------
  1234. #-----------------------------------------------------------------------------
  1235. # TraitTypes subclasses for handling classes and instances of classes
  1236. #-----------------------------------------------------------------------------
  1237. class ClassBasedTraitType(TraitType):
  1238. """
  1239. A trait with error reporting and string -> type resolution for Type,
  1240. Instance and This.
  1241. """
  1242. def _resolve_string(self, string):
  1243. """
  1244. Resolve a string supplied for a type into an actual object.
  1245. """
  1246. return import_item(string)
  1247. def error(self, obj, value):
  1248. kind = type(value)
  1249. if six.PY2 and kind is InstanceType:
  1250. msg = 'class %s' % value.__class__.__name__
  1251. else:
  1252. msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
  1253. if obj is not None:
  1254. e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
  1255. % (self.name, class_of(obj),
  1256. self.info(), msg)
  1257. else:
  1258. e = "The '%s' trait must be %s, but a value of %r was specified." \
  1259. % (self.name, self.info(), msg)
  1260. raise TraitError(e)
  1261. class Type(ClassBasedTraitType):
  1262. """A trait whose value must be a subclass of a specified class."""
  1263. def __init__ (self, default_value=Undefined, klass=None, **kwargs):
  1264. """Construct a Type trait
  1265. A Type trait specifies that its values must be subclasses of
  1266. a particular class.
  1267. If only ``default_value`` is given, it is used for the ``klass`` as
  1268. well. If neither are given, both default to ``object``.
  1269. Parameters
  1270. ----------
  1271. default_value : class, str or None
  1272. The default value must be a subclass of klass. If an str,
  1273. the str must be a fully specified class name, like 'foo.bar.Bah'.
  1274. The string is resolved into real class, when the parent
  1275. :class:`HasTraits` class is instantiated.
  1276. klass : class, str [ default object ]
  1277. Values of this trait must be a subclass of klass. The klass
  1278. may be specified in a string like: 'foo.bar.MyClass'.
  1279. The string is resolved into real class, when the parent
  1280. :class:`HasTraits` class is instantiated.
  1281. allow_none : bool [ default False ]
  1282. Indicates whether None is allowed as an assignable value.
  1283. """
  1284. if default_value is Undefined:
  1285. new_default_value = object if (klass is None) else klass
  1286. else:
  1287. new_default_value = default_value
  1288. if klass is None:
  1289. if (default_value is None) or (default_value is Undefined):
  1290. klass = object
  1291. else:
  1292. klass = default_value
  1293. if not (inspect.isclass(klass) or isinstance(klass, six.string_types)):
  1294. raise TraitError("A Type trait must specify a class.")
  1295. self.klass = klass
  1296. super(Type, self).__init__(new_default_value, **kwargs)
  1297. def validate(self, obj, value):
  1298. """Validates that the value is a valid object instance."""
  1299. if isinstance(value, six.string_types):
  1300. try:
  1301. value = self._resolve_string(value)
  1302. except ImportError:
  1303. raise TraitError("The '%s' trait of %s instance must be a type, but "
  1304. "%r could not be imported" % (self.name, obj, value))
  1305. try:
  1306. if issubclass(value, self.klass):
  1307. return value
  1308. except:
  1309. pass
  1310. self.error(obj, value)
  1311. def info(self):
  1312. """ Returns a description of the trait."""
  1313. if isinstance(self.klass, six.string_types):
  1314. klass = self.klass
  1315. else:
  1316. klass = self.klass.__module__ + '.' + self.klass.__name__
  1317. result = "a subclass of '%s'" % klass
  1318. if self.allow_none:
  1319. return result + ' or None'
  1320. return result
  1321. def instance_init(self, obj):
  1322. self._resolve_classes()
  1323. super(Type, self).instance_init(obj)
  1324. def _resolve_classes(self):
  1325. if isinstance(self.klass, six.string_types):
  1326. self.klass = self._resolve_string(self.klass)
  1327. if isinstance(self.default_value, six.string_types):
  1328. self.default_value = self._resolve_string(self.default_value)
  1329. def default_value_repr(self):
  1330. value = self.default_value
  1331. if isinstance(value, six.string_types):
  1332. return repr(value)
  1333. else:
  1334. return repr('{}.{}'.format(value.__module__, value.__name__))
  1335. class Instance(ClassBasedTraitType):
  1336. """A trait whose value must be an instance of a specified class.
  1337. The value can also be an instance of a subclass of the specified class.
  1338. Subclasses can declare default classes by overriding the klass attribute
  1339. """
  1340. klass = None
  1341. def __init__(self, klass=None, args=None, kw=None, **kwargs):
  1342. """Construct an Instance trait.
  1343. This trait allows values that are instances of a particular
  1344. class or its subclasses. Our implementation is quite different
  1345. from that of enthough.traits as we don't allow instances to be used
  1346. for klass and we handle the ``args`` and ``kw`` arguments differently.
  1347. Parameters
  1348. ----------
  1349. klass : class, str
  1350. The class that forms the basis for the trait. Class names
  1351. can also be specified as strings, like 'foo.bar.Bar'.
  1352. args : tuple
  1353. Positional arguments for generating the default value.
  1354. kw : dict
  1355. Keyword arguments for generating the default value.
  1356. allow_none : bool [ default False ]
  1357. Indicates whether None is allowed as a value.
  1358. Notes
  1359. -----
  1360. If both ``args`` and ``kw`` are None, then the default value is None.
  1361. If ``args`` is a tuple and ``kw`` is a dict, then the default is
  1362. created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
  1363. None, the None is replaced by ``()`` or ``{}``, respectively.
  1364. """
  1365. if klass is None:
  1366. klass = self.klass
  1367. if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, six.string_types)):
  1368. self.klass = klass
  1369. else:
  1370. raise TraitError('The klass attribute must be a class'
  1371. ' not: %r' % klass)
  1372. if (kw is not None) and not isinstance(kw, dict):
  1373. raise TraitError("The 'kw' argument must be a dict or None.")
  1374. if (args is not None) and not isinstance(args, tuple):
  1375. raise TraitError("The 'args' argument must be a tuple or None.")
  1376. self.default_args = args
  1377. self.default_kwargs = kw
  1378. super(Instance, self).__init__(**kwargs)
  1379. def validate(self, obj, value):
  1380. if isinstance(value, self.klass):
  1381. return value
  1382. else:
  1383. self.error(obj, value)
  1384. def info(self):
  1385. if isinstance(self.klass, six.string_types):
  1386. klass = self.klass
  1387. else:
  1388. klass = self.klass.__name__
  1389. result = class_of(klass)
  1390. if self.allow_none:
  1391. return result + ' or None'
  1392. return result
  1393. def instance_init(self, obj):
  1394. self._resolve_classes()
  1395. super(Instance, self).instance_init(obj)
  1396. def _resolve_classes(self):
  1397. if isinstance(self.klass, six.string_types):
  1398. self.klass = self._resolve_string(self.klass)
  1399. def make_dynamic_default(self):
  1400. if (self.default_args is None) and (self.default_kwargs is None):
  1401. return None
  1402. return self.klass(*(self.default_args or ()),
  1403. **(self.default_kwargs or {}))
  1404. def default_value_repr(self):
  1405. return repr(self.make_dynamic_default())
  1406. class ForwardDeclaredMixin(object):
  1407. """
  1408. Mixin for forward-declared versions of Instance and Type.
  1409. """
  1410. def _resolve_string(self, string):
  1411. """
  1412. Find the specified class name by looking for it in the module in which
  1413. our this_class attribute was defined.
  1414. """
  1415. modname = self.this_class.__module__
  1416. return import_item('.'.join([modname, string]))
  1417. class ForwardDeclaredType(ForwardDeclaredMixin, Type):
  1418. """
  1419. Forward-declared version of Type.
  1420. """
  1421. pass
  1422. class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
  1423. """
  1424. Forward-declared version of Instance.
  1425. """
  1426. pass
  1427. class This(ClassBasedTraitType):
  1428. """A trait for instances of the class containing this trait.
  1429. Because how how and when class bodies are executed, the ``This``
  1430. trait can only have a default value of None. This, and because we
  1431. always validate default values, ``allow_none`` is *always* true.
  1432. """
  1433. info_text = 'an instance of the same type as the receiver or None'
  1434. def __init__(self, **kwargs):
  1435. super(This, self).__init__(None, **kwargs)
  1436. def validate(self, obj, value):
  1437. # What if value is a superclass of obj.__class__? This is
  1438. # complicated if it was the superclass that defined the This
  1439. # trait.
  1440. if isinstance(value, self.this_class) or (value is None):
  1441. return value
  1442. else:
  1443. self.error(obj, value)
  1444. class Union(TraitType):
  1445. """A trait type representing a Union type."""
  1446. def __init__(self, trait_types, **kwargs):
  1447. """Construct a Union trait.
  1448. This trait allows values that are allowed by at least one of the
  1449. specified trait types. A Union traitlet cannot have metadata on
  1450. its own, besides the metadata of the listed types.
  1451. Parameters
  1452. ----------
  1453. trait_types: sequence
  1454. The list of trait types of length at least 1.
  1455. Notes
  1456. -----
  1457. Union([Float(), Bool(), Int()]) attempts to validate the provided values
  1458. with the validation function of Float, then Bool, and finally Int.
  1459. """
  1460. self.trait_types = trait_types
  1461. self.info_text = " or ".join([tt.info() for tt in self.trait_types])
  1462. super(Union, self).__init__(**kwargs)
  1463. def class_init(self, cls, name):
  1464. for trait_type in self.trait_types:
  1465. trait_type.class_init(cls, None)
  1466. super(Union, self).class_init(cls, name)
  1467. def instance_init(self, obj):
  1468. for trait_type in self.trait_types:
  1469. trait_type.instance_init(obj)
  1470. super(Union, self).instance_init(obj)
  1471. def validate(self, obj, value):
  1472. with obj.cross_validation_lock:
  1473. for trait_type in self.trait_types:
  1474. try:
  1475. v = trait_type._validate(obj, value)
  1476. # In the case of an element trait, the name is None
  1477. if self.name is not None:
  1478. setattr(obj, '_' + self.name + '_metadata', trait_type.metadata)
  1479. return v
  1480. except TraitError:
  1481. continue
  1482. self.error(obj, value)
  1483. def __or__(self, other):
  1484. if isinstance(other, Union):
  1485. return Union(self.trait_types + other.trait_types)
  1486. else:
  1487. return Union(self.trait_types + [other])
  1488. def make_dynamic_default(self):
  1489. if self.default_value is not Undefined:
  1490. return self.default_value
  1491. for trait_type in self.trait_types:
  1492. if trait_type.default_value is not Undefined:
  1493. return trait_type.default_value
  1494. elif hasattr(trait_type, 'make_dynamic_default'):
  1495. return trait_type.make_dynamic_default()
  1496. #-----------------------------------------------------------------------------
  1497. # Basic TraitTypes implementations/subclasses
  1498. #-----------------------------------------------------------------------------
  1499. class Any(TraitType):
  1500. """A trait which allows any value."""
  1501. default_value = None
  1502. info_text = 'any value'
  1503. def _validate_bounds(trait, obj, value):
  1504. """
  1505. Validate that a number to be applied to a trait is between bounds.
  1506. If value is not between min_bound and max_bound, this raises a
  1507. TraitError with an error message appropriate for this trait.
  1508. """
  1509. if trait.min is not None and value < trait.min:
  1510. raise TraitError(
  1511. "The value of the '{name}' trait of {klass} instance should "
  1512. "not be less than {min_bound}, but a value of {value} was "
  1513. "specified".format(
  1514. name=trait.name, klass=class_of(obj),
  1515. value=value, min_bound=trait.min))
  1516. if trait.max is not None and value > trait.max:
  1517. raise TraitError(
  1518. "The value of the '{name}' trait of {klass} instance should "
  1519. "not be greater than {max_bound}, but a value of {value} was "
  1520. "specified".format(
  1521. name=trait.name, klass=class_of(obj),
  1522. value=value, max_bound=trait.max))
  1523. return value
  1524. class Int(TraitType):
  1525. """An int trait."""
  1526. default_value = 0
  1527. info_text = 'an int'
  1528. def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
  1529. self.min = kwargs.pop('min', None)
  1530. self.max = kwargs.pop('max', None)
  1531. super(Int, self).__init__(default_value=default_value,
  1532. allow_none=allow_none, **kwargs)
  1533. def validate(self, obj, value):
  1534. if not isinstance(value, int):
  1535. self.error(obj, value)
  1536. return _validate_bounds(self, obj, value)
  1537. class CInt(Int):
  1538. """A casting version of the int trait."""
  1539. def validate(self, obj, value):
  1540. try:
  1541. value = int(value)
  1542. except:
  1543. self.error(obj, value)
  1544. return _validate_bounds(self, obj, value)
  1545. if six.PY2:
  1546. class Long(TraitType):
  1547. """A long integer trait."""
  1548. default_value = 0
  1549. info_text = 'a long'
  1550. def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
  1551. self.min = kwargs.pop('min', None)
  1552. self.max = kwargs.pop('max', None)
  1553. super(Long, self).__init__(
  1554. default_value=default_value,
  1555. allow_none=allow_none, **kwargs)
  1556. def _validate_long(self, obj, value):
  1557. if isinstance(value, long):
  1558. return value
  1559. if isinstance(value, int):
  1560. return long(value)
  1561. self.error(obj, value)
  1562. def validate(self, obj, value):
  1563. value = self._validate_long(obj, value)
  1564. return _validate_bounds(self, obj, value)
  1565. class CLong(Long):
  1566. """A casting version of the long integer trait."""
  1567. def validate(self, obj, value):
  1568. try:
  1569. value = long(value)
  1570. except:
  1571. self.error(obj, value)
  1572. return _validate_bounds(self, obj, value)
  1573. class Integer(TraitType):
  1574. """An integer trait.
  1575. Longs that are unnecessary (<= sys.maxint) are cast to ints."""
  1576. default_value = 0
  1577. info_text = 'an integer'
  1578. def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
  1579. self.min = kwargs.pop('min', None)
  1580. self.max = kwargs.pop('max', None)
  1581. super(Integer, self).__init__(
  1582. default_value=default_value,
  1583. allow_none=allow_none, **kwargs)
  1584. def _validate_int(self, obj, value):
  1585. if isinstance(value, int):
  1586. return value
  1587. if isinstance(value, long):
  1588. # downcast longs that fit in int:
  1589. # note that int(n > sys.maxint) returns a long, so
  1590. # we don't need a condition on this cast
  1591. return int(value)
  1592. if sys.platform == "cli":
  1593. from System import Int64
  1594. if isinstance(value, Int64):
  1595. return int(value)
  1596. self.error(obj, value)
  1597. def validate(self, obj, value):
  1598. value = self._validate_int(obj, value)
  1599. return _validate_bounds(self, obj, value)
  1600. else:
  1601. Long, CLong = Int, CInt
  1602. Integer = Int
  1603. class Float(TraitType):
  1604. """A float trait."""
  1605. default_value = 0.0
  1606. info_text = 'a float'
  1607. def __init__(self, default_value=Undefined, allow_none=False, **kwargs):
  1608. self.min = kwargs.pop('min', -float('inf'))
  1609. self.max = kwargs.pop('max', float('inf'))
  1610. super(Float, self).__init__(default_value=default_value,
  1611. allow_none=allow_none, **kwargs)
  1612. def validate(self, obj, value):
  1613. if isinstance(value, int):
  1614. value = float(value)
  1615. if not isinstance(value, float):
  1616. self.error(obj, value)
  1617. return _validate_bounds(self, obj, value)
  1618. class CFloat(Float):
  1619. """A casting version of the float trait."""
  1620. def validate(self, obj, value):
  1621. try:
  1622. value = float(value)
  1623. except:
  1624. self.error(obj, value)
  1625. return _validate_bounds(self, obj, value)
  1626. class Complex(TraitType):
  1627. """A trait for complex numbers."""
  1628. default_value = 0.0 + 0.0j
  1629. info_text = 'a complex number'
  1630. def validate(self, obj, value):
  1631. if isinstance(value, complex):
  1632. return value
  1633. if isinstance(value, (float, int)):
  1634. return complex(value)
  1635. self.error(obj, value)
  1636. class CComplex(Complex):
  1637. """A casting version of the complex number trait."""
  1638. def validate (self, obj, value):
  1639. try:
  1640. return complex(value)
  1641. except:
  1642. self.error(obj, value)
  1643. # We should always be explicit about whether we're using bytes or unicode, both
  1644. # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
  1645. # we don't have a Str type.
  1646. class Bytes(TraitType):
  1647. """A trait for byte strings."""
  1648. default_value = b''
  1649. info_text = 'a bytes object'
  1650. def validate(self, obj, value):
  1651. if isinstance(value, bytes):
  1652. return value
  1653. self.error(obj, value)
  1654. class CBytes(Bytes):
  1655. """A casting version of the byte string trait."""
  1656. def validate(self, obj, value):
  1657. try:
  1658. return bytes(value)
  1659. except:
  1660. self.error(obj, value)
  1661. class Unicode(TraitType):
  1662. """A trait for unicode strings."""
  1663. default_value = u''
  1664. info_text = 'a unicode string'
  1665. def validate(self, obj, value):
  1666. if isinstance(value, six.text_type):
  1667. return value
  1668. if isinstance(value, bytes):
  1669. try:
  1670. return value.decode('ascii', 'strict')
  1671. except UnicodeDecodeError:
  1672. msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
  1673. raise TraitError(msg.format(value, self.name, class_of(obj)))
  1674. self.error(obj, value)
  1675. class CUnicode(Unicode):
  1676. """A casting version of the unicode trait."""
  1677. def validate(self, obj, value):
  1678. try:
  1679. return six.text_type(value)
  1680. except:
  1681. self.error(obj, value)
  1682. class ObjectName(TraitType):
  1683. """A string holding a valid object name in this version of Python.
  1684. This does not check that the name exists in any scope."""
  1685. info_text = "a valid object identifier in Python"
  1686. if six.PY2:
  1687. # Python 2:
  1688. def coerce_str(self, obj, value):
  1689. "In Python 2, coerce ascii-only unicode to str"
  1690. if isinstance(value, unicode):
  1691. try:
  1692. return str(value)
  1693. except UnicodeEncodeError:
  1694. self.error(obj, value)
  1695. return value
  1696. else:
  1697. coerce_str = staticmethod(lambda _,s: s)
  1698. def validate(self, obj, value):
  1699. value = self.coerce_str(obj, value)
  1700. if isinstance(value, six.string_types) and isidentifier(value):
  1701. return value
  1702. self.error(obj, value)
  1703. class DottedObjectName(ObjectName):
  1704. """A string holding a valid dotted object name in Python, such as A.b3._c"""
  1705. def validate(self, obj, value):
  1706. value = self.coerce_str(obj, value)
  1707. if isinstance(value, six.string_types) and all(isidentifier(a)
  1708. for a in value.split('.')):
  1709. return value
  1710. self.error(obj, value)
  1711. class Bool(TraitType):
  1712. """A boolean (True, False) trait."""
  1713. default_value = False
  1714. info_text = 'a boolean'
  1715. def validate(self, obj, value):
  1716. if isinstance(value, bool):
  1717. return value
  1718. self.error(obj, value)
  1719. class CBool(Bool):
  1720. """A casting version of the boolean trait."""
  1721. def validate(self, obj, value):
  1722. try:
  1723. return bool(value)
  1724. except:
  1725. self.error(obj, value)
  1726. class Enum(TraitType):
  1727. """An enum whose value must be in a given sequence."""
  1728. def __init__(self, values, default_value=Undefined, **kwargs):
  1729. self.values = values
  1730. if kwargs.get('allow_none', False) and default_value is Undefined:
  1731. default_value = None
  1732. super(Enum, self).__init__(default_value, **kwargs)
  1733. def validate(self, obj, value):
  1734. if value in self.values:
  1735. return value
  1736. self.error(obj, value)
  1737. def info(self):
  1738. """ Returns a description of the trait."""
  1739. result = 'any of ' + repr(self.values)
  1740. if self.allow_none:
  1741. return result + ' or None'
  1742. return result
  1743. class CaselessStrEnum(Enum):
  1744. """An enum of strings where the case should be ignored."""
  1745. def __init__(self, values, default_value=Undefined, **kwargs):
  1746. values = [cast_unicode_py2(value) for value in values]
  1747. super(CaselessStrEnum, self).__init__(values, default_value=default_value, **kwargs)
  1748. def validate(self, obj, value):
  1749. if isinstance(value, str):
  1750. value = cast_unicode_py2(value)
  1751. if not isinstance(value, six.string_types):
  1752. self.error(obj, value)
  1753. for v in self.values:
  1754. if v.lower() == value.lower():
  1755. return v
  1756. self.error(obj, value)
  1757. class Container(Instance):
  1758. """An instance of a container (list, set, etc.)
  1759. To be subclassed by overriding klass.
  1760. """
  1761. klass = None
  1762. _cast_types = ()
  1763. _valid_defaults = SequenceTypes
  1764. _trait = None
  1765. def __init__(self, trait=None, default_value=None, **kwargs):
  1766. """Create a container trait type from a list, set, or tuple.
  1767. The default value is created by doing ``List(default_value)``,
  1768. which creates a copy of the ``default_value``.
  1769. ``trait`` can be specified, which restricts the type of elements
  1770. in the container to that TraitType.
  1771. If only one arg is given and it is not a Trait, it is taken as
  1772. ``default_value``:
  1773. ``c = List([1, 2, 3])``
  1774. Parameters
  1775. ----------
  1776. trait : TraitType [ optional ]
  1777. the type for restricting the contents of the Container. If unspecified,
  1778. types are not checked.
  1779. default_value : SequenceType [ optional ]
  1780. The default value for the Trait. Must be list/tuple/set, and
  1781. will be cast to the container type.
  1782. allow_none : bool [ default False ]
  1783. Whether to allow the value to be None
  1784. **kwargs : any
  1785. further keys for extensions to the Trait (e.g. config)
  1786. """
  1787. # allow List([values]):
  1788. if default_value is None and not is_trait(trait):
  1789. default_value = trait
  1790. trait = None
  1791. if default_value is None:
  1792. args = ()
  1793. elif isinstance(default_value, self._valid_defaults):
  1794. args = (default_value,)
  1795. else:
  1796. raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
  1797. if is_trait(trait):
  1798. if isinstance(trait, type):
  1799. warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)."
  1800. " Passing types is deprecated in traitlets 4.1.",
  1801. DeprecationWarning, stacklevel=3)
  1802. self._trait = trait() if isinstance(trait, type) else trait
  1803. elif trait is not None:
  1804. raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
  1805. super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
  1806. def element_error(self, obj, element, validator):
  1807. e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
  1808. % (self.name, class_of(obj), validator.info(), repr_type(element))
  1809. raise TraitError(e)
  1810. def validate(self, obj, value):
  1811. if isinstance(value, self._cast_types):
  1812. value = self.klass(value)
  1813. value = super(Container, self).validate(obj, value)
  1814. if value is None:
  1815. return value
  1816. value = self.validate_elements(obj, value)
  1817. return value
  1818. def validate_elements(self, obj, value):
  1819. validated = []
  1820. if self._trait is None or isinstance(self._trait, Any):
  1821. return value
  1822. for v in value:
  1823. try:
  1824. v = self._trait._validate(obj, v)
  1825. except TraitError:
  1826. self.element_error(obj, v, self._trait)
  1827. else:
  1828. validated.append(v)
  1829. return self.klass(validated)
  1830. def class_init(self, cls, name):
  1831. if isinstance(self._trait, TraitType):
  1832. self._trait.class_init(cls, None)
  1833. super(Container, self).class_init(cls, name)
  1834. def instance_init(self, obj):
  1835. if isinstance(self._trait, TraitType):
  1836. self._trait.instance_init(obj)
  1837. super(Container, self).instance_init(obj)
  1838. class List(Container):
  1839. """An instance of a Python list."""
  1840. klass = list
  1841. _cast_types = (tuple,)
  1842. def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **kwargs):
  1843. """Create a List trait type from a list, set, or tuple.
  1844. The default value is created by doing ``list(default_value)``,
  1845. which creates a copy of the ``default_value``.
  1846. ``trait`` can be specified, which restricts the type of elements
  1847. in the container to that TraitType.
  1848. If only one arg is given and it is not a Trait, it is taken as
  1849. ``default_value``:
  1850. ``c = List([1, 2, 3])``
  1851. Parameters
  1852. ----------
  1853. trait : TraitType [ optional ]
  1854. the type for restricting the contents of the Container.
  1855. If unspecified, types are not checked.
  1856. default_value : SequenceType [ optional ]
  1857. The default value for the Trait. Must be list/tuple/set, and
  1858. will be cast to the container type.
  1859. minlen : Int [ default 0 ]
  1860. The minimum length of the input list
  1861. maxlen : Int [ default sys.maxsize ]
  1862. The maximum length of the input list
  1863. """
  1864. self._minlen = minlen
  1865. self._maxlen = maxlen
  1866. super(List, self).__init__(trait=trait, default_value=default_value,
  1867. **kwargs)
  1868. def length_error(self, obj, value):
  1869. e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
  1870. % (self.name, class_of(obj), self._minlen, self._maxlen, value)
  1871. raise TraitError(e)
  1872. def validate_elements(self, obj, value):
  1873. length = len(value)
  1874. if length < self._minlen or length > self._maxlen:
  1875. self.length_error(obj, value)
  1876. return super(List, self).validate_elements(obj, value)
  1877. def validate(self, obj, value):
  1878. value = super(List, self).validate(obj, value)
  1879. value = self.validate_elements(obj, value)
  1880. return value
  1881. class Set(List):
  1882. """An instance of a Python set."""
  1883. klass = set
  1884. _cast_types = (tuple, list)
  1885. # Redefine __init__ just to make the docstring more accurate.
  1886. def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,
  1887. **kwargs):
  1888. """Create a Set trait type from a list, set, or tuple.
  1889. The default value is created by doing ``set(default_value)``,
  1890. which creates a copy of the ``default_value``.
  1891. ``trait`` can be specified, which restricts the type of elements
  1892. in the container to that TraitType.
  1893. If only one arg is given and it is not a Trait, it is taken as
  1894. ``default_value``:
  1895. ``c = Set({1, 2, 3})``
  1896. Parameters
  1897. ----------
  1898. trait : TraitType [ optional ]
  1899. the type for restricting the contents of the Container.
  1900. If unspecified, types are not checked.
  1901. default_value : SequenceType [ optional ]
  1902. The default value for the Trait. Must be list/tuple/set, and
  1903. will be cast to the container type.
  1904. minlen : Int [ default 0 ]
  1905. The minimum length of the input list
  1906. maxlen : Int [ default sys.maxsize ]
  1907. The maximum length of the input list
  1908. """
  1909. super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs)
  1910. class Tuple(Container):
  1911. """An instance of a Python tuple."""
  1912. klass = tuple
  1913. _cast_types = (list,)
  1914. def __init__(self, *traits, **kwargs):
  1915. """Create a tuple from a list, set, or tuple.
  1916. Create a fixed-type tuple with Traits:
  1917. ``t = Tuple(Int(), Str(), CStr())``
  1918. would be length 3, with Int,Str,CStr for each element.
  1919. If only one arg is given and it is not a Trait, it is taken as
  1920. default_value:
  1921. ``t = Tuple((1, 2, 3))``
  1922. Otherwise, ``default_value`` *must* be specified by keyword.
  1923. Parameters
  1924. ----------
  1925. `*traits` : TraitTypes [ optional ]
  1926. the types for restricting the contents of the Tuple. If unspecified,
  1927. types are not checked. If specified, then each positional argument
  1928. corresponds to an element of the tuple. Tuples defined with traits
  1929. are of fixed length.
  1930. default_value : SequenceType [ optional ]
  1931. The default value for the Tuple. Must be list/tuple/set, and
  1932. will be cast to a tuple. If ``traits`` are specified,
  1933. ``default_value`` must conform to the shape and type they specify.
  1934. """
  1935. default_value = kwargs.pop('default_value', Undefined)
  1936. # allow Tuple((values,)):
  1937. if len(traits) == 1 and default_value is Undefined and not is_trait(traits[0]):
  1938. default_value = traits[0]
  1939. traits = ()
  1940. if default_value is Undefined:
  1941. args = ()
  1942. elif isinstance(default_value, self._valid_defaults):
  1943. args = (default_value,)
  1944. else:
  1945. raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
  1946. self._traits = []
  1947. for trait in traits:
  1948. if isinstance(trait, type):
  1949. warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
  1950. " Passing types is deprecated in traitlets 4.1.",
  1951. DeprecationWarning, stacklevel=2)
  1952. t = trait() if isinstance(trait, type) else trait
  1953. self._traits.append(t)
  1954. if self._traits and default_value is None:
  1955. # don't allow default to be an empty container if length is specified
  1956. args = None
  1957. super(Container,self).__init__(klass=self.klass, args=args, **kwargs)
  1958. def validate_elements(self, obj, value):
  1959. if not self._traits:
  1960. # nothing to validate
  1961. return value
  1962. if len(value) != len(self._traits):
  1963. e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
  1964. % (self.name, class_of(obj), len(self._traits), repr_type(value))
  1965. raise TraitError(e)
  1966. validated = []
  1967. for t, v in zip(self._traits, value):
  1968. try:
  1969. v = t._validate(obj, v)
  1970. except TraitError:
  1971. self.element_error(obj, v, t)
  1972. else:
  1973. validated.append(v)
  1974. return tuple(validated)
  1975. def class_init(self, cls, name):
  1976. for trait in self._traits:
  1977. if isinstance(trait, TraitType):
  1978. trait.class_init(cls, None)
  1979. super(Container, self).class_init(cls, name)
  1980. def instance_init(self, obj):
  1981. for trait in self._traits:
  1982. if isinstance(trait, TraitType):
  1983. trait.instance_init(obj)
  1984. super(Container, self).instance_init(obj)
  1985. class Dict(Instance):
  1986. """An instance of a Python dict."""
  1987. _trait = None
  1988. def __init__(self, trait=None, traits=None, default_value=Undefined,
  1989. **kwargs):
  1990. """Create a dict trait type from a Python dict.
  1991. The default value is created by doing ``dict(default_value)``,
  1992. which creates a copy of the ``default_value``.
  1993. Parameters
  1994. ----------
  1995. trait : TraitType [ optional ]
  1996. The specified trait type to check and use to restrict contents of
  1997. the Container. If unspecified, trait types are not checked.
  1998. traits : Dictionary of trait types [ optional ]
  1999. A Python dictionary containing the types that are valid for
  2000. restricting the content of the Dict Container for certain keys.
  2001. default_value : SequenceType [ optional ]
  2002. The default value for the Dict. Must be dict, tuple, or None, and
  2003. will be cast to a dict if not None. If `trait` is specified, the
  2004. `default_value` must conform to the constraints it specifies.
  2005. """
  2006. # Handling positional arguments
  2007. if default_value is Undefined and trait is not None:
  2008. if not is_trait(trait):
  2009. default_value = trait
  2010. trait = None
  2011. # Handling default value
  2012. if default_value is Undefined:
  2013. default_value = {}
  2014. if default_value is None:
  2015. args = None
  2016. elif isinstance(default_value, dict):
  2017. args = (default_value,)
  2018. elif isinstance(default_value, SequenceTypes):
  2019. args = (default_value,)
  2020. else:
  2021. raise TypeError('default value of Dict was %s' % default_value)
  2022. # Case where a type of TraitType is provided rather than an instance
  2023. if is_trait(trait):
  2024. if isinstance(trait, type):
  2025. warn("Traits should be given as instances, not types (for example, `Int()`, not `Int`)"
  2026. " Passing types is deprecated in traitlets 4.1.",
  2027. DeprecationWarning, stacklevel=2)
  2028. self._trait = trait() if isinstance(trait, type) else trait
  2029. elif trait is not None:
  2030. raise TypeError("`trait` must be a Trait or None, got %s" % repr_type(trait))
  2031. self._traits = traits
  2032. super(Dict, self).__init__(klass=dict, args=args, **kwargs)
  2033. def element_error(self, obj, element, validator):
  2034. e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
  2035. % (self.name, class_of(obj), validator.info(), repr_type(element))
  2036. raise TraitError(e)
  2037. def validate(self, obj, value):
  2038. value = super(Dict, self).validate(obj, value)
  2039. if value is None:
  2040. return value
  2041. value = self.validate_elements(obj, value)
  2042. return value
  2043. def validate_elements(self, obj, value):
  2044. use_dict = bool(self._traits)
  2045. default_to = (self._trait or Any())
  2046. if not use_dict and isinstance(default_to, Any):
  2047. return value
  2048. validated = {}
  2049. for key in value:
  2050. if use_dict and key in self._traits:
  2051. validate_with = self._traits[key]
  2052. else:
  2053. validate_with = default_to
  2054. try:
  2055. v = value[key]
  2056. if not isinstance(validate_with, Any):
  2057. v = validate_with._validate(obj, v)
  2058. except TraitError:
  2059. self.element_error(obj, v, validate_with)
  2060. else:
  2061. validated[key] = v
  2062. return self.klass(validated)
  2063. def class_init(self, cls, name):
  2064. if isinstance(self._trait, TraitType):
  2065. self._trait.class_init(cls, None)
  2066. if self._traits is not None:
  2067. for trait in self._traits.values():
  2068. trait.class_init(cls, None)
  2069. super(Dict, self).class_init(cls, name)
  2070. def instance_init(self, obj):
  2071. if isinstance(self._trait, TraitType):
  2072. self._trait.instance_init(obj)
  2073. if self._traits is not None:
  2074. for trait in self._traits.values():
  2075. trait.instance_init(obj)
  2076. super(Dict, self).instance_init(obj)
  2077. class TCPAddress(TraitType):
  2078. """A trait for an (ip, port) tuple.
  2079. This allows for both IPv4 IP addresses as well as hostnames.
  2080. """
  2081. default_value = ('127.0.0.1', 0)
  2082. info_text = 'an (ip, port) tuple'
  2083. def validate(self, obj, value):
  2084. if isinstance(value, tuple):
  2085. if len(value) == 2:
  2086. if isinstance(value[0], six.string_types) and isinstance(value[1], int):
  2087. port = value[1]
  2088. if port >= 0 and port <= 65535:
  2089. return value
  2090. self.error(obj, value)
  2091. class CRegExp(TraitType):
  2092. """A casting compiled regular expression trait.
  2093. Accepts both strings and compiled regular expressions. The resulting
  2094. attribute will be a compiled regular expression."""
  2095. info_text = 'a regular expression'
  2096. def validate(self, obj, value):
  2097. try:
  2098. return re.compile(value)
  2099. except:
  2100. self.error(obj, value)
  2101. class UseEnum(TraitType):
  2102. """Use a Enum class as model for the data type description.
  2103. Note that if no default-value is provided, the first enum-value is used
  2104. as default-value.
  2105. .. sourcecode:: python
  2106. # -- SINCE: Python 3.4 (or install backport: pip install enum34)
  2107. import enum
  2108. from traitlets import HasTraits, UseEnum
  2109. class Color(enum.Enum):
  2110. red = 1 # -- IMPLICIT: default_value
  2111. blue = 2
  2112. green = 3
  2113. class MyEntity(HasTraits):
  2114. color = UseEnum(Color, default_value=Color.blue)
  2115. entity = MyEntity(color=Color.red)
  2116. entity.color = Color.green # USE: Enum-value (preferred)
  2117. entity.color = "green" # USE: name (as string)
  2118. entity.color = "Color.green" # USE: scoped-name (as string)
  2119. entity.color = 3 # USE: number (as int)
  2120. assert entity.color is Color.green
  2121. """
  2122. default_value = None
  2123. info_text = "Trait type adapter to a Enum class"
  2124. def __init__(self, enum_class, default_value=None, **kwargs):
  2125. assert issubclass(enum_class, enum.Enum), \
  2126. "REQUIRE: enum.Enum, but was: %r" % enum_class
  2127. allow_none = kwargs.get("allow_none", False)
  2128. if default_value is None and not allow_none:
  2129. default_value = list(enum_class.__members__.values())[0]
  2130. super(UseEnum, self).__init__(default_value=default_value, **kwargs)
  2131. self.enum_class = enum_class
  2132. self.name_prefix = enum_class.__name__ + "."
  2133. def select_by_number(self, value, default=Undefined):
  2134. """Selects enum-value by using its number-constant."""
  2135. assert isinstance(value, int)
  2136. enum_members = self.enum_class.__members__
  2137. for enum_item in enum_members.values():
  2138. if enum_item.value == value:
  2139. return enum_item
  2140. # -- NOT FOUND:
  2141. return default
  2142. def select_by_name(self, value, default=Undefined):
  2143. """Selects enum-value by using its name or scoped-name."""
  2144. assert isinstance(value, six.string_types)
  2145. if value.startswith(self.name_prefix):
  2146. # -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
  2147. value = value.replace(self.name_prefix, "", 1)
  2148. return self.enum_class.__members__.get(value, default)
  2149. def validate(self, obj, value):
  2150. if isinstance(value, self.enum_class):
  2151. return value
  2152. elif isinstance(value, int):
  2153. # -- CONVERT: number => enum_value (item)
  2154. value2 = self.select_by_number(value)
  2155. if value2 is not Undefined:
  2156. return value2
  2157. elif isinstance(value, six.string_types):
  2158. # -- CONVERT: name or scoped_name (as string) => enum_value (item)
  2159. value2 = self.select_by_name(value)
  2160. if value2 is not Undefined:
  2161. return value2
  2162. elif value is None:
  2163. if self.allow_none:
  2164. return None
  2165. else:
  2166. return self.default_value
  2167. self.error(obj, value)
  2168. def info(self):
  2169. """Returns a description of this Enum trait (in case of errors)."""
  2170. result = "Any of: %s" % ", ".join(self.enum_class.__members__.keys())
  2171. if self.allow_none:
  2172. return result + " or None"
  2173. return result