##// END OF EJS Templates
Merge pull request #8226 from minrk/errant-session...
Merge pull request #8226 from minrk/errant-session remove errant IPython.kernel.session.py

File last commit:

r21045:12680619
r21075:2a9139a3 merge
Show More
traitlets.py
1878 lines | 61.3 KiB | text/x-python | PythonLexer
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 # encoding: utf-8
"""
A lightweight Traits like module.
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 This is designed to provide a lightweight, simple, pure Python version of
many of the capabilities of enthought.traits. This includes:
* Validation
* Type specification with defaults
* Static and dynamic notification
* Basic predefined types
* An API that is similar to enthought.traits
We don't support:
* Delegation
* Automatic GUI generation
Brian Granger
A few more small traitlets features.
r2179 * A full set of trait types. Most importantly, we don't provide container
Dav Clark
Final changes traitlet -> trait for review
r2385 traits (list, dict, tuple) that can trigger notifications if their
Brian Granger
A few more small traitlets features.
r2179 contents change.
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 * API compatibility with enthought.traits
Brian Granger
A few more small traitlets features.
r2179 There are also some important difference in our design:
* enthought.traits does not validate default values. We do.
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 We choose to create this module because we need these capabilities, but
we need them to be pure Python so they work in all Python implementations,
including Jython and IronPython.
Thomas Kluyver
Only include inheritance diagram where it's useful.
r8795 Inheritance diagram:
.. inheritance-diagram:: IPython.utils.traitlets
:parts: 3
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """
Min RK
Make HasTraits pickleable...
r16216 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #
Min RK
Make HasTraits pickleable...
r16216 # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
# also under the terms of the Modified BSD License.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Jason Grout
Add a convenience class to sync traitlet attributes
r15008 import contextlib
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 import inspect
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 import re
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 import sys
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 import types
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 from types import FunctionType
try:
from types import ClassType, InstanceType
ClassTypes = (ClassType, type)
except:
ClassTypes = (type,)
Scott Sanderson
DOC: Warn the user when they pass `default` to a TraitType....
r20649 from warnings import warn
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 from IPython.utils import py3compat
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560 from IPython.utils import eventful
Min RK
update traitlets imports
r20998 from IPython.utils.getargspec import getargspec
Matthias Bussonnier
make sentinel class for some kwargs....
r21045 from IPython.utils.signatures import Sentinel
Min RK
update traitlets imports
r20998 from IPython.utils.importstring import import_item
MinRK
fix some string_types checks in traitlets...
r18124 from IPython.utils.py3compat import iteritems, string_types
Jonathan Frederic
Skip the doc tests for Connect,...
r15011 from IPython.testing.skipdoctest import skip_doctest
Brian Granger
A number of changes to how traitlets and components work....
r2229
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 SequenceTypes = (list, tuple, set, frozenset)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
# Basic classes
#-----------------------------------------------------------------------------
Matthias Bussonnier
make sentinel class for some kwargs....
r21045 NoDefaultSpecified = Sentinel('NoDefaultSpecified', __name__,
'''
Used in Traitlets to specify that no defaults are set in kwargs
'''
)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
class Undefined ( object ): pass
Undefined = Undefined()
Dav Clark
Iniital stab at renames for traitlets
r2384 class TraitError(Exception):
pass
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
#-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance( object, py3compat.string_types ):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return add_article( object )
return add_article( object.__class__.__name__ )
def add_article ( name ):
""" Returns a string containing the correct indefinite article ('a' or 'an')
prefixed to the specified string.
"""
if name[:1].lower() in 'aeiou':
return 'an ' + name
return 'a ' + name
def repr_type(obj):
""" Return a string representation of a value and its type for readable
error messages.
"""
the_type = type(obj)
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 if (not py3compat.PY3) and the_type is InstanceType:
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 # Old-style class.
the_type = obj.__class__
msg = '%r %r' % (obj, the_type)
return msg
epatters
BUG: Traitlets now accepts instantiated sub-traits in List, Tuple, etc....
r8407 def is_trait(t):
""" Returns whether the given value is an instance or subclass of TraitType.
"""
return (isinstance(t, TraitType) or
(isinstance(t, type) and issubclass(t, TraitType)))
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 def parse_notifier_name(name):
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 """Convert the name argument to a list of names.
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 Examples
--------
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 >>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
Dav Clark
Iniital stab at renames for traitlets
r2384 ['anytrait']
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 """
MinRK
fix some string_types checks in traitlets...
r18124 if isinstance(name, string_types):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return [name]
elif name is None:
Dav Clark
Iniital stab at renames for traitlets
r2384 return ['anytrait']
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 elif isinstance(name, (list, tuple)):
for n in name:
MinRK
fix some string_types checks in traitlets...
r18124 assert isinstance(n, string_types), "names must be strings"
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return name
Brian Granger
Improvement to how config is handled in Components....
r2184
class _SimpleTest:
def __init__ ( self, value ): self.value = value
def __call__ ( self, test ):
return test == self.value
def __repr__(self):
return "<SimpleTest(%r)" % self.value
def __str__(self):
return self.__repr__()
Brian Granger
Work on refactoring ipcontroller to new config system.
r2287 def getmembers(object, predicate=None):
"""A safe version of inspect.getmembers that handles missing attributes.
Bernardo B. Marques
remove all trailling spaces
r4872 This is useful when there are descriptor based attributes that for
Brian Granger
Work on refactoring ipcontroller to new config system.
r2287 some reason raise AttributeError even though they exist. This happens
in zope.inteface with the __provides__ attribute.
"""
results = []
for key in dir(object):
try:
value = getattr(object, key)
except AttributeError:
pass
else:
if not predicate or predicate(value):
results.append((key, value))
results.sort()
return results
Min RK
validate args in traitlets.link, dlink
r20076 def _validate_link(*tuples):
"""Validate arguments for traitlet link functions"""
for t in tuples:
if not len(t) == 2:
raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
obj, trait_name = t
if not isinstance(obj, HasTraits):
raise TypeError("Each object must be HasTraits, not %r" % type(obj))
if not trait_name in obj.traits():
raise TypeError("%r has no trait %r" % (obj, trait_name))
Jonathan Frederic
Skip the doc tests for Connect,...
r15011 @skip_doctest
Jason Grout
Change 'bind' to 'link'
r15163 class link(object):
"""Link traits from different objects together so they remain in sync.
Jason Grout
Add a convenience class to sync traitlet attributes
r15008
Parameters
----------
Min RK
validate args in traitlets.link, dlink
r20076 *args : pairs of objects/attributes
Jason Grout
Add a convenience class to sync traitlet attributes
r15008
Examples
--------
Jason Grout
Change 'bind' to 'link'
r15163 >>> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value'))
Jason Grout
Add a convenience class to sync traitlet attributes
r15008 >>> obj1.value = 5 # updates other objects as well
"""
updating = False
def __init__(self, *args):
Jonathan Frederic
fixes to make Connect pass tests
r15013 if len(args) < 2:
raise TypeError('At least two traitlets must be provided.')
Min RK
validate args in traitlets.link, dlink
r20076 _validate_link(*args)
Jonathan Frederic
fixes to make Connect pass tests
r15013
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 self.objects = {}
Sylvain Corlay
Remove comparisons in traitlet links
r18989
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 initial = getattr(args[0][0], args[0][1])
Sylvain Corlay
Remove comparisons in traitlet links
r18989 for obj, attr in args:
setattr(obj, attr, initial)
Jason Grout
Add a convenience class to sync traitlet attributes
r15008
Sylvain Corlay
Remove comparisons in traitlet links
r18989 callback = self._make_closure(obj, attr)
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 obj.on_trait_change(callback, attr)
Sylvain Corlay
Remove comparisons in traitlet links
r18989 self.objects[(obj, attr)] = callback
Jonathan Frederic
fixes to make Connect pass tests
r15013
Jason Grout
Add a convenience class to sync traitlet attributes
r15008 @contextlib.contextmanager
def _busy_updating(self):
self.updating = True
Jonathan Frederic
Added try/finally
r15009 try:
yield
finally:
self.updating = False
Jason Grout
Add a convenience class to sync traitlet attributes
r15008
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 def _make_closure(self, sending_obj, sending_attr):
def update(name, old, new):
self._update(sending_obj, sending_attr, new)
return update
def _update(self, sending_obj, sending_attr, new):
Jason Grout
Add a convenience class to sync traitlet attributes
r15008 if self.updating:
return
with self._busy_updating():
Sylvain Corlay
Remove comparisons in traitlet links
r18989 for obj, attr in self.objects.keys():
setattr(obj, attr, new)
Jason Grout
Change 'bind' to 'link'
r15163 def unlink(self):
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 for key, callback in self.objects.items():
Sylvain Corlay
Remove comparisons in traitlet links
r18989 (obj, attr) = key
Jonathan Frederic
Use closure to prevent traitlet callbacks from firing twice.
r15018 obj.on_trait_change(callback, attr, remove=True)
Brian Granger
Work on refactoring ipcontroller to new config system.
r2287
Sylvain Corlay
unidirectional link of traitlets
r17627 @skip_doctest
Sylvain Corlay
renaming unilink to directional_link and adding dlink alias
r17629 class directional_link(object):
Sylvain Corlay
unidirectional link of traitlets
r17627 """Link the trait of a source object with traits of target objects.
Parameters
----------
source : pair of object, name
targets : pairs of objects/attributes
Examples
--------
Sylvain Corlay
renaming unilink to directional_link and adding dlink alias
r17629 >>> c = directional_link((src, 'value'), (tgt1, 'value'), (tgt2, 'value'))
Sylvain Corlay
unidirectional link of traitlets
r17627 >>> src.value = 5 # updates target objects
>>> tgt1.value = 6 # does not update other objects
"""
updating = False
def __init__(self, source, *targets):
Min RK
validate args in traitlets.link, dlink
r20076 if len(targets) < 1:
raise TypeError('At least two traitlets must be provided.')
_validate_link(source, *targets)
Sylvain Corlay
unidirectional link of traitlets
r17627 self.source = source
self.targets = targets
# Update current value
src_attr_value = getattr(source[0], source[1])
for obj, attr in targets:
Sylvain Corlay
Remove comparisons in traitlet links
r18989 setattr(obj, attr, src_attr_value)
Sylvain Corlay
unidirectional link of traitlets
r17627
# Wire
self.source[0].on_trait_change(self._update, self.source[1])
@contextlib.contextmanager
def _busy_updating(self):
self.updating = True
try:
yield
finally:
self.updating = False
def _update(self, name, old, new):
if self.updating:
return
with self._busy_updating():
for obj, attr in self.targets:
setattr(obj, attr, new)
def unlink(self):
Sylvain Corlay
wrong callback
r17628 self.source[0].on_trait_change(self._update, self.source[1], remove=True)
Sylvain Corlay
unidirectional link of traitlets
r17627 self.source = None
self.targets = []
Min RK
validate args in traitlets.link, dlink
r20076 dlink = directional_link
Sylvain Corlay
renaming unilink to directional_link and adding dlink alias
r17629
Johan Forsberg
support functools.partial as traitlet callback
r19991
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 # Base TraitType for all traits
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 class TraitType(object):
"""A base class for all trait descriptors.
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183
Notes
-----
Dav Clark
Final changes traitlet -> trait for review
r2385 Our implementation of traits is based on Python's descriptor
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 prototol. This class is the base class for all such descriptors. The
Dav Clark
Iniital stab at renames for traitlets
r2384 only magic we use is a custom metaclass for the main :class:`HasTraits`
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 class that does the following:
Dav Clark
Final changes traitlet -> trait for review
r2385 1. Sets the :attr:`name` attribute of every :class:`TraitType`
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 instance in the class dict to the name of the attribute.
Dav Clark
Final changes traitlet -> trait for review
r2385 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
instance in the class dict to the *class* that declared the trait.
This is used by the :class:`This` trait to allow subclasses to
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 accept superclasses for :class:`This` values.
"""
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 metadata = {}
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 default_value = Undefined
zah
Implementation in TraitType directly.
r16453 allow_none = False
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 info_text = 'any value'
zah
Implementation in TraitType directly.
r16453 def __init__(self, default_value=NoDefaultSpecified, allow_none=None, **metadata):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Create a TraitType.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 if default_value is not NoDefaultSpecified:
self.default_value = default_value
zah
Implementation in TraitType directly.
r16453 if allow_none is not None:
self.allow_none = allow_none
Brian Granger
Improvement to how config is handled in Components....
r2184
Scott Sanderson
DOC: Warn the user when they pass `default` to a TraitType....
r20649 if 'default' in metadata:
# Warn the user that they probably meant default_value.
warn(
"Parameter 'default' passed to TraitType. "
"Did you mean 'default_value'?"
)
Brian Granger
Improvement to how config is handled in Components....
r2184 if len(metadata) > 0:
if len(self.metadata) > 0:
self._metadata = self.metadata.copy()
self._metadata.update(metadata)
else:
self._metadata = metadata
else:
self._metadata = self.metadata
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 self.init()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 def init(self):
pass
def get_default_value(self):
"""Create a new instance of the default value."""
Brian Granger
Minor work on kernelmanager....
r2742 return self.default_value
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
"""Part of the initialization which may depends on the underlying
HasTraits instance.
It is typically overloaded for specific trait types.
This method is called by :meth:`HasTraits.__new__` and in the
:meth:`TraitType.instance_init` method of trait types holding
other trait types.
"""
Sylvain Corlay
Split instance_init in two
r20786 pass
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def init_default_value(self, obj):
"""Instantiate the default value for the trait type.
This method is called by :meth:`TraitType.set_default_value` in the
case a default value is provided at construction time or later when
accessing the trait value for the first time in
:meth:`HasTraits.__get__`.
"""
Sylvain Corlay
handle failed test
r20787 value = self.get_default_value()
value = self._validate(obj, value)
obj._trait_values[self.name] = value
return value
Brian Granger
Important changes to simplify traitlets....
r2182 def set_default_value(self, obj):
Brian Granger
A number of changes to how traitlets and components work....
r2229 """Set the default value on a per instance basis.
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 This method is called by :meth:`HasTraits.__new__` to instantiate and
validate the default value. The creation and validation of
Dav Clark
Iniital stab at renames for traitlets
r2384 default values must be delayed until the parent :class:`HasTraits`
Brian Granger
A number of changes to how traitlets and components work....
r2229 class has been instantiated.
Sylvain Corlay
some cleanup
r20788 Parameters
----------
obj : :class:`HasTraits` instance
The parent :class:`HasTraits` instance that has just been
created.
Brian Granger
A number of changes to how traitlets and components work....
r2229 """
Robert Kern
ENH: Add dynamic initializers (_x_default methods) to traitlets.
r3207 # Check for a deferred initializer defined in the same class as the
# trait declaration or above.
mro = type(obj).mro()
meth_name = '_%s_default' % self.name
for cls in mro[:mro.index(self.this_class)+1]:
if meth_name in cls.__dict__:
break
else:
Sylvain Corlay
some cleanup
r20788 # We didn't find one. Do static initialization.
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 self.init_default_value(obj)
Robert Kern
ENH: Add dynamic initializers (_x_default methods) to traitlets.
r3207 return
# Complete the dynamic initialization.
Min RK
Make HasTraits pickleable...
r16216 obj._trait_dyn_inits[self.name] = meth_name
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790
Brian Granger
Important changes to simplify traitlets....
r2182 def __get__(self, obj, cls=None):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Get the value of the trait by self.name for the instance.
Brian Granger
Improvements to component.py....
r2180
Dav Clark
Iniital stab at renames for traitlets
r2384 Default values are instantiated when :meth:`HasTraits.__new__`
Bernardo B. Marques
remove all trailling spaces
r4872 is called. Thus by the time this method gets called either the
Brian Granger
Important changes to simplify traitlets....
r2182 default value or a user defined value (they called :meth:`__set__`)
Dav Clark
Iniital stab at renames for traitlets
r2384 is in the :class:`HasTraits` instance.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """
if obj is None:
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return self
else:
Brian Granger
Important changes to simplify traitlets....
r2182 try:
Dav Clark
Final changes traitlet -> trait for review
r2385 value = obj._trait_values[self.name]
Robert Kern
ENH: Add dynamic initializers (_x_default methods) to traitlets.
r3207 except KeyError:
# Check for a dynamic initializer.
Robert Kern
BUG: Do not store class-specific state on TraitTypes since they may be shared through subclassing.
r3336 if self.name in obj._trait_dyn_inits:
Min RK
Make HasTraits pickleable...
r16216 method = getattr(obj, obj._trait_dyn_inits[self.name])
value = method()
Robert Kern
ENH: Add dynamic initializers (_x_default methods) to traitlets.
r3207 # FIXME: Do we really validate here?
value = self._validate(obj, value)
obj._trait_values[self.name] = value
return value
else:
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 return self.init_default_value(obj)
Robert Kern
ENH: Add dynamic initializers (_x_default methods) to traitlets.
r3207 except Exception:
Dav Clark
Iniital stab at renames for traitlets
r2384 # HasTraits should call set_default_value to populate
Brian Granger
Important changes to simplify traitlets....
r2182 # this. So this should never be reached.
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError('Unexpected error in TraitType: '
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 'default value not set properly')
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 else:
Brian Granger
Important changes to simplify traitlets....
r2182 return value
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Brian Granger
Important changes to simplify traitlets....
r2182 def __set__(self, obj, value):
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 new_value = self._validate(obj, value)
Thomas Kluyver
Don't calculate default value when setting traitlet for the first time
r19121 try:
old_value = obj._trait_values[self.name]
except KeyError:
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 old_value = Undefined
Thomas Kluyver
Don't calculate default value when setting traitlet for the first time
r19121
MinRK
always perform requested trait assignments...
r8230 obj._trait_values[self.name] = new_value
Jason Grout
If there is an error comparing traitlet values when setting a trait, default to go ahead and notify of the new value.
r15436 try:
Jason Grout
Make traitlets notify check more robust against classes redefining equality and bool...
r15462 silent = bool(old_value == new_value)
Jason Grout
If there is an error comparing traitlet values when setting a trait, default to go ahead and notify of the new value.
r15436 except:
# if there is an error in comparing, default to notify
Jason Grout
Make traitlets notify check more robust against classes redefining equality and bool...
r15462 silent = False
if silent is not True:
# we explicitly compare silent to True just in case the equality
# comparison above returns something other than True/False
Dav Clark
Final changes traitlet -> trait for review
r2385 obj._notify_trait(self.name, old_value, new_value)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 def _validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if value is None and self.allow_none:
return value
Sylvain Corlay
removed unused code is_valid_for and value_for
r20520 if hasattr(self, 'validate'):
value = self.validate(obj, value)
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 if obj._cross_validation_lock is False:
value = self._cross_validate(obj, value)
return value
def _cross_validate(self, obj, value):
if hasattr(obj, '_%s_validate' % self.name):
cross_validate = getattr(obj, '_%s_validate' % self.name)
value = cross_validate(value, self)
Sylvain Corlay
removed unused code is_valid_for and value_for
r20520 return value
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Sylvain Corlay
Overload __or__ on traitlets and add a test
r18977 def __or__(self, other):
if isinstance(other, Union):
return Union([self] + other.trait_types)
else:
return Union([self, other])
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 def info(self):
return self.info_text
def error(self, obj, value):
if obj is not None:
Dav Clark
Final changes traitlet -> trait for review
r2385 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 % (self.name, class_of(obj),
self.info(), repr_type(value))
else:
Dav Clark
Final changes traitlet -> trait for review
r2385 e = "The '%s' trait must be %s, but a value of %r was specified." \
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 % (self.name, self.info(), repr_type(value))
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError(e)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Jason Grout
Add an optional `default` argument to trait metadata get, like the Python dict's .get() default argument...
r17673 def get_metadata(self, key, default=None):
return getattr(self, '_metadata', {}).get(key, default)
Brian Granger
Improvement to how config is handled in Components....
r2184
def set_metadata(self, key, value):
getattr(self, '_metadata', {})[key] = value
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
#-----------------------------------------------------------------------------
Dav Clark
Iniital stab at renames for traitlets
r2384 # The HasTraits implementation
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
Dav Clark
Iniital stab at renames for traitlets
r2384 class MetaHasTraits(type):
"""A metaclass for HasTraits.
Bernardo B. Marques
remove all trailling spaces
r4872
Dav Clark
Final changes traitlet -> trait for review
r2385 This metaclass makes sure that any TraitType class attributes are
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 instantiated and sets their name attribute.
"""
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 def __new__(mcls, name, bases, classdict):
Dav Clark
Iniital stab at renames for traitlets
r2384 """Create the HasTraits class.
Bernardo B. Marques
remove all trailling spaces
r4872
Dav Clark
Final changes traitlet -> trait for review
r2385 This instantiates all TraitTypes in the class dict and sets their
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 :attr:`name` attribute.
"""
Brian Granger
Work on refactoring ipcontroller to new config system.
r2287 # print "MetaHasTraitlets (mcls, name): ", mcls, name
# print "MetaHasTraitlets (bases): ", bases
# print "MetaHasTraitlets (classdict): ", classdict
Thomas Kluyver
Fix references to dict.iteritems and dict.itervalues
r13361 for k,v in iteritems(classdict):
Dav Clark
Final changes traitlet -> trait for review
r2385 if isinstance(v, TraitType):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 v.name = k
elif inspect.isclass(v):
Dav Clark
Final changes traitlet -> trait for review
r2385 if issubclass(v, TraitType):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 vinst = v()
vinst.name = k
classdict[k] = vinst
Dav Clark
Iniital stab at renames for traitlets
r2384 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 def __init__(cls, name, bases, classdict):
Dav Clark
Iniital stab at renames for traitlets
r2384 """Finish initializing the HasTraits class.
Bernardo B. Marques
remove all trailling spaces
r4872
Dav Clark
Final changes traitlet -> trait for review
r2385 This sets the :attr:`this_class` attribute of each TraitType in the
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 class dict to the newly created class ``cls``.
"""
Thomas Kluyver
Fix references to dict.iteritems and dict.itervalues
r13361 for k, v in iteritems(classdict):
Dav Clark
Final changes traitlet -> trait for review
r2385 if isinstance(v, TraitType):
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 v.this_class = cls
Dav Clark
Iniital stab at renames for traitlets
r2384 super(MetaHasTraits, cls).__init__(name, bases, classdict)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Sylvain Corlay
Hold validation with context manager and validate slider
r20950
Thomas Kluyver
Fixes for metaclass syntax
r13359 class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
MinRK
add ignored *args to HasTraits constructor...
r10257 def __new__(cls, *args, **kw):
Matthias BUSSONNIER
remove confusing mention of 2.6
r16320 # This is needed because object.__new__ only accepts
Brian Granger
Fixed Python 2.6 warning with traitlets object.__new__....
r2255 # the cls argument.
Dav Clark
Iniital stab at renames for traitlets
r2384 new_meth = super(HasTraits, cls).__new__
Brian Granger
Fixed Python 2.6 warning with traitlets object.__new__....
r2255 if new_meth is object.__new__:
inst = new_meth(cls)
else:
Brian Granger
Allow trait values to be set in the keyword arguments of __init__.
r2739 inst = new_meth(cls, **kw)
Dav Clark
Final changes traitlet -> trait for review
r2385 inst._trait_values = {}
inst._trait_notifiers = {}
Robert Kern
BUG: Do not store class-specific state on TraitTypes since they may be shared through subclassing.
r3336 inst._trait_dyn_inits = {}
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 inst._cross_validation_lock = True
Dav Clark
Final changes traitlet -> trait for review
r2385 # Here we tell all the TraitType instances to set their default
Bernardo B. Marques
remove all trailling spaces
r4872 # values on the instance.
Brian Granger
Important changes to simplify traitlets....
r2182 for key in dir(cls):
Brian Granger
Work on refactoring ipcontroller to new config system.
r2287 # Some descriptors raise AttributeError like zope.interface's
# __provides__ attributes even though they exist. This causes
# AttributeErrors even though they are listed in dir(cls).
try:
value = getattr(cls, key)
except AttributeError:
pass
else:
Dav Clark
merged from ~fdo.perez/ipython/trunk-dev
r2469 if isinstance(value, TraitType):
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 value.instance_init()
Sylvain Corlay
Split instance_init in two
r20786 if key not in kw:
Sylvain Corlay
some cleanup
r20788 value.set_default_value(inst)
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 inst._cross_validation_lock = False
Brian Granger
Important changes to simplify traitlets....
r2182 return inst
MinRK
add ignored *args to HasTraits constructor...
r10257 def __init__(self, *args, **kw):
Brian Granger
Adding support for HasTraits to take keyword arguments.
r2740 # Allow trait values to be set using keyword arguments.
Brian Granger
Fixing bugs and adding comment
r2745 # We need to use setattr for this to trigger validation and
# notifications.
Min RK
s/delay_trait_notifications/hold_trait_notifications/
r20808 with self.hold_trait_notifications():
Min RK
add HasTraits.delay_trait_notifications...
r20805 for key, value in iteritems(kw):
setattr(self, key, value)
Sylvain Corlay
Hold validation with context manager and validate slider
r20950
Min RK
add HasTraits.delay_trait_notifications...
r20805 @contextlib.contextmanager
Min RK
s/delay_trait_notifications/hold_trait_notifications/
r20808 def hold_trait_notifications(self):
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 """Context manager for bundling trait change notifications and cross
validation.
Use this when doing multiple trait assignments (init, config), to avoid
race conditions in trait notifiers requesting other trait values.
Min RK
add HasTraits.delay_trait_notifications...
r20805 All trait notifications will fire after all values have been assigned.
"""
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 if self._cross_validation_lock is True:
Min RK
add HasTraits.delay_trait_notifications...
r20805 yield
Sylvain Corlay
Adding a test for rollback in case of rejection
r20979 return
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 else:
self._cross_validation_lock = True
cache = {}
notifications = {}
_notify_trait = self._notify_trait
def cache_values(*a):
cache[a[0]] = a
def hold_notifications(*a):
notifications[a[0]] = a
self._notify_trait = cache_values
try:
yield
finally:
try:
self._notify_trait = hold_notifications
for name in cache:
if hasattr(self, '_%s_validate' % name):
cross_validate = getattr(self, '_%s_validate' % name)
setattr(self, name, cross_validate(getattr(self, name), self))
except TraitError as e:
self._notify_trait = lambda *x: None
for name in cache:
if cache[name][1] is not Undefined:
setattr(self, name, cache[name][1])
Sylvain Corlay
Aggregate notifications / Use delattr in rollbacks due to bulk rejection
r20961 else:
delattr(self, name)
Sylvain Corlay
Fix wrong behavior in case of bulk rejection
r20963 cache = {}
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 notifications = {}
raise e
finally:
self._notify_trait = _notify_trait
Sylvain Corlay
Adding a test for rollback in case of rejection
r20979 self._cross_validation_lock = False
Sylvain Corlay
Hold validation with context manager and validate slider
r20950 if isinstance(_notify_trait, types.MethodType):
# FIXME: remove when support is bumped to 3.4.
# when original method is restored,
# remove the redundant value from __dict__
# (only used to preserve pickleability on Python < 3.4)
self.__dict__.pop('_notify_trait', None)
# trigger delayed notifications
Sylvain Corlay
Aggregate notifications / Use delattr in rollbacks due to bulk rejection
r20961 for v in dict(cache, **notifications).values():
self._notify_trait(*v)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Dav Clark
Final changes traitlet -> trait for review
r2385 def _notify_trait(self, name, old_value, new_value):
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175
# First dynamic ones
Jonathan Frederic
Fix traitlet _notify_trait by-ref issue
r13148 callables = []
callables.extend(self._trait_notifiers.get(name,[]))
callables.extend(self._trait_notifiers.get('anytrait',[]))
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175
# Now static ones
try:
cb = getattr(self, '_%s_changed' % name)
except:
pass
else:
callables.append(cb)
# Call them all now
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 for c in callables:
# Traits catches and logs errors here. I allow them to raise
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 if callable(c):
Johan Forsberg
support functools.partial as traitlet callback
r19991 argspec = getargspec(c)
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 nargs = len(argspec[0])
# Bound methods have an additional 'self' argument
# I don't know how to treat unbound methods, but they
# can't really be used for callbacks.
if isinstance(c, types.MethodType):
offset = -1
else:
offset = 0
if nargs + offset == 0:
c()
elif nargs + offset == 1:
c(name)
elif nargs + offset == 2:
c(name, new_value)
elif nargs + offset == 3:
c(name, old_value, new_value)
else:
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError('a trait changed callback '
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 'must have 0-3 arguments.')
else:
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError('a trait changed callback '
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 'must be callable.')
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
def _add_notifiers(self, handler, name):
Bradley M. Froehle
2to3: Apply has_key fixer.
r7859 if name not in self._trait_notifiers:
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 nlist = []
Dav Clark
Final changes traitlet -> trait for review
r2385 self._trait_notifiers[name] = nlist
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 else:
Dav Clark
Final changes traitlet -> trait for review
r2385 nlist = self._trait_notifiers[name]
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 if handler not in nlist:
nlist.append(handler)
def _remove_notifiers(self, handler, name):
Bradley M. Froehle
2to3: Apply has_key fixer.
r7859 if name in self._trait_notifiers:
Dav Clark
Final changes traitlet -> trait for review
r2385 nlist = self._trait_notifiers[name]
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 try:
index = nlist.index(handler)
except ValueError:
pass
else:
del nlist[index]
Dav Clark
Iniital stab at renames for traitlets
r2384 def on_trait_change(self, handler, name=None, remove=False):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Setup a handler to be called when a trait changes.
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175
Dav Clark
Final changes traitlet -> trait for review
r2385 This is used to setup dynamic notifications of trait changes.
Bernardo B. Marques
remove all trailling spaces
r4872
Dav Clark
Iniital stab at renames for traitlets
r2384 Static handlers can be created by creating methods on a HasTraits
Dav Clark
Final changes traitlet -> trait for review
r2385 subclass with the naming convention '_[traitname]_changed'. Thus,
to create static handler for the trait 'a', create the method
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 _a_changed(self, name, old, new) (fewer arguments can be used, see
below).
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 Parameters
----------
Brian Granger
Major work on the documentation....
r2277 handler : callable
Bernardo B. Marques
remove all trailling spaces
r4872 A callable that is called when a trait changes. Its
Brian Granger
Major work on the documentation....
r2277 signature can be handler(), handler(name), handler(name, new)
or handler(name, old, new).
name : list, str, None
Dav Clark
Final changes traitlet -> trait for review
r2385 If None, the handler will apply to all traits. If a list
Brian Granger
Major work on the documentation....
r2277 of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
remove : bool
If False (the default), then install the handler. If True
then unintall it.
Brian Granger
More work on traitlets.py. I have added tests for existing traitlets.
r2175 """
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 if remove:
names = parse_notifier_name(name)
for n in names:
self._remove_notifiers(handler, n)
else:
names = parse_notifier_name(name)
for n in names:
self._add_notifiers(handler, n)
Brian Granger
Ongoing work on the config system....
r3789 @classmethod
def class_trait_names(cls, **metadata):
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 """Get a list of all the names of this class' traits.
Brian Granger
Ongoing work on the config system....
r3789
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 This method is just like the :meth:`trait_names` method,
but is unbound.
Brian Granger
Ongoing work on the config system....
r3789 """
return cls.class_traits(**metadata).keys()
@classmethod
def class_traits(cls, **metadata):
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 """Get a `dict` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
Brian Granger
Ongoing work on the config system....
r3789
This method is just like the :meth:`traits` method, but is unbound.
The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. This does not allow for any simple way of
testing that a metadata name exists and has any
value because get_metadata returns None if a metadata key
doesn't exist.
Brian Granger
Ongoing work on the config system....
r3789 """
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 traits = dict([memb for memb in getmembers(cls) if
Brian Granger
Ongoing work on the config system....
r3789 isinstance(memb[1], TraitType)])
if len(metadata) == 0:
return traits
for meta_name, meta_eval in metadata.items():
if type(meta_eval) is not FunctionType:
metadata[meta_name] = _SimpleTest(meta_eval)
result = {}
for name, trait in traits.items():
for meta_name, meta_eval in metadata.items():
if not meta_eval(trait.get_metadata(meta_name)):
break
else:
result[name] = trait
return result
Dav Clark
Iniital stab at renames for traitlets
r2384 def trait_names(self, **metadata):
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 """Get a list of all the names of this class' traits."""
Dav Clark
Iniital stab at renames for traitlets
r2384 return self.traits(**metadata).keys()
Brian Granger
Improvement to how config is handled in Components....
r2184
Dav Clark
Iniital stab at renames for traitlets
r2384 def traits(self, **metadata):
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 """Get a `dict` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
Brian Granger
Improvement to how config is handled in Components....
r2184
Dav Clark
Final changes traitlet -> trait for review
r2385 The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.
Brian Granger
Massive refactoring of of the core....
r2245
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. This does not allow for any simple way of
testing that a metadata name exists and has any
value because get_metadata returns None if a metadata key
doesn't exist.
Brian Granger
Improvement to how config is handled in Components....
r2184 """
Thomas A Caswell
DOC : modified docs is HasTraits.traits and HasTraits.class_traits...
r15487 traits = dict([memb for memb in getmembers(self.__class__) if
Dav Clark
Final changes traitlet -> trait for review
r2385 isinstance(memb[1], TraitType)])
Brian Granger
Improvement to how config is handled in Components....
r2184
Brian Granger
Massive refactoring of of the core....
r2245 if len(metadata) == 0:
Dav Clark
Final changes traitlet -> trait for review
r2385 return traits
Brian Granger
Semi-final Application and minor work on traitlets.
r2200
Brian Granger
Improvement to how config is handled in Components....
r2184 for meta_name, meta_eval in metadata.items():
if type(meta_eval) is not FunctionType:
metadata[meta_name] = _SimpleTest(meta_eval)
result = {}
Dav Clark
Final changes traitlet -> trait for review
r2385 for name, trait in traits.items():
Brian Granger
Improvement to how config is handled in Components....
r2184 for meta_name, meta_eval in metadata.items():
Dav Clark
Final changes traitlet -> trait for review
r2385 if not meta_eval(trait.get_metadata(meta_name)):
Brian Granger
Improvement to how config is handled in Components....
r2184 break
else:
Dav Clark
Final changes traitlet -> trait for review
r2385 result[name] = trait
Brian Granger
Improvement to how config is handled in Components....
r2184
return result
Brian Granger
A few more small traitlets features.
r2179
Jason Grout
Add an optional `default` argument to trait metadata get, like the Python dict's .get() default argument...
r17673 def trait_metadata(self, traitname, key, default=None):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Get metadata values for trait by key."""
Brian Granger
Improvement to how config is handled in Components....
r2184 try:
Dav Clark
Final changes traitlet -> trait for review
r2385 trait = getattr(self.__class__, traitname)
Brian Granger
Improvement to how config is handled in Components....
r2184 except AttributeError:
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError("Class %s does not have a trait named %s" %
(self.__class__.__name__, traitname))
Brian Granger
Improvement to how config is handled in Components....
r2184 else:
Jason Grout
Add an optional `default` argument to trait metadata get, like the Python dict's .get() default argument...
r17673 return trait.get_metadata(key, default)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Jonathan Frederic
Dynamic traits.
r20828 def add_trait(self, traitname, trait):
"""Dynamically add a trait attribute to the HasTraits instance."""
self.__class__ = type(self.__class__.__name__, (self.__class__,),
{traitname: trait})
trait.set_default_value(self)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 # Actual TraitTypes implementations/subclasses
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #-----------------------------------------------------------------------------
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
#-----------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 # TraitTypes subclasses for handling classes and instances of classes
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 #-----------------------------------------------------------------------------
zah
Implementation in TraitType directly.
r16453 class ClassBasedTraitType(TraitType):
Scott Sanderson
DOC: Clarify docstring for `ClassBasedTraitType`.
r18777 """
A trait with error reporting and string -> type resolution for Type,
Instance and This.
"""
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Scott Sanderson
DEV: Support default_value in `ForwardDeclaredMixin`.
r18775 def _resolve_string(self, string):
"""
Resolve a string supplied for a type into an actual object.
"""
return import_item(string)
Brian Granger
Important changes to simplify traitlets....
r2182 def error(self, obj, value):
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 kind = type(value)
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 if (not py3compat.PY3) and kind is InstanceType:
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Dav Clark
Final changes traitlet -> trait for review
r2385 class Type(ClassBasedTraitType):
"""A trait whose value must be a subclass of a specified class."""
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Sylvain Corlay
allow_none=False by default for Type and Instance
r20940 def __init__ (self, default_value=None, klass=None, allow_none=False,
**metadata):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Construct a Type trait
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Dav Clark
Final changes traitlet -> trait for review
r2385 A Type trait specifies that its values must be subclasses of
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 a particular class.
Brian Granger
A number of changes to how traitlets and components work....
r2229 If only ``default_value`` is given, it is used for the ``klass`` as
well.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 Parameters
----------
Brian Granger
A number of changes to how traitlets and components work....
r2229 default_value : class, str or None
The default value must be a subclass of klass. If an str,
the str must be a fully specified class name, like 'foo.bar.Bah'.
Bernardo B. Marques
remove all trailling spaces
r4872 The string is resolved into real class, when the parent
Dav Clark
Iniital stab at renames for traitlets
r2384 :class:`HasTraits` class is instantiated.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 klass : class, str, None
Dav Clark
Final changes traitlet -> trait for review
r2385 Values of this trait must be a subclass of klass. The klass
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 may be specified in a string like: 'foo.bar.MyClass'.
Bernardo B. Marques
remove all trailling spaces
r4872 The string is resolved into real class, when the parent
Dav Clark
Iniital stab at renames for traitlets
r2384 :class:`HasTraits` class is instantiated.
Sylvain Corlay
doc fix
r20482 allow_none : bool [ default True ]
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 Indicates whether None is allowed as an assignable value. Even if
``False``, the default value may be ``None``.
"""
if default_value is None:
if klass is None:
klass = object
elif klass is None:
klass = default_value
Thomas Kluyver
Replace references to unicode and basestring
r13353 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError("A Type trait must specify a class.")
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
self.klass = klass
zah
Used **kwargs in initializers.
r16544 super(Type, self).__init__(default_value, allow_none=allow_none, **metadata)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
def validate(self, obj, value):
"""Validates that the value is a valid object instance."""
Thomas Kluyver
Allow Type trait to be set with an importable string
r16961 if isinstance(value, py3compat.string_types):
try:
Scott Sanderson
DEV: Convert a stray import_item -> self._resolve_string.
r18776 value = self._resolve_string(value)
Thomas Kluyver
Allow Type trait to be set with an importable string
r16961 except ImportError:
raise TraitError("The '%s' trait of %s instance must be a type, but "
Sylvain Corlay
simplify decorate
r20789 "%r could not be imported" % (self.name, obj, value))
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 try:
if issubclass(value, self.klass):
return value
except:
zah
Implementation in TraitType directly.
r16453 pass
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
self.error(obj, value)
def info(self):
""" Returns a description of the trait."""
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(self.klass, py3compat.string_types):
Brian Granger
A number of changes to how traitlets and components work....
r2229 klass = self.klass
else:
klass = self.klass.__name__
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 result = 'a subclass of ' + klass
zah
Implementation in TraitType directly.
r16453 if self.allow_none:
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 return result + ' or None'
return result
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Brian Granger
A number of changes to how traitlets and components work....
r2229 self._resolve_classes()
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 super(Type, self).instance_init()
Brian Granger
A number of changes to how traitlets and components work....
r2229
def _resolve_classes(self):
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(self.klass, py3compat.string_types):
Scott Sanderson
DEV: Support default_value in `ForwardDeclaredMixin`.
r18775 self.klass = self._resolve_string(self.klass)
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(self.default_value, py3compat.string_types):
Scott Sanderson
DEV: Support default_value in `ForwardDeclaredMixin`.
r18775 self.default_value = self._resolve_string(self.default_value)
Brian Granger
A number of changes to how traitlets and components work....
r2229
def get_default_value(self):
return self.default_value
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
class DefaultValueGenerator(object):
"""A class for generating new default value instances."""
Brian Granger
A number of changes to how traitlets and components work....
r2229 def __init__(self, *args, **kw):
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 self.args = args
self.kw = kw
Brian Granger
A number of changes to how traitlets and components work....
r2229 def generate(self, klass):
return klass(*self.args, **self.kw)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Brian Granger
Important changes to simplify traitlets....
r2182
Dav Clark
Final changes traitlet -> trait for review
r2385 class Instance(ClassBasedTraitType):
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """A trait whose value must be an instance of a specified class.
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 The value can also be an instance of a subclass of the specified class.
Jason Grout
Give subclasses of the Instance traitlet the option of overriding the klass variable to have a default klass....
r17238
Subclasses can declare default classes by overriding the klass attribute
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """
Jason Grout
Give subclasses of the Instance traitlet the option of overriding the klass variable to have a default klass....
r17238 klass = None
Sylvain Corlay
allow_none=False by default for Type and Instance
r20940 def __init__(self, klass=None, args=None, kw=None, allow_none=False,
**metadata ):
Dav Clark
Final changes traitlet -> trait for review
r2385 """Construct an Instance trait.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Dav Clark
Final changes traitlet -> trait for review
r2385 This trait allows values that are instances of a particular
Sylvain Corlay
A Union Traitlet
r18972 class or its subclasses. Our implementation is quite different
Brian Granger
Important changes to simplify traitlets....
r2182 from that of enthough.traits as we don't allow instances to be used
for klass and we handle the ``args`` and ``kw`` arguments differently.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 Parameters
----------
Brian Granger
A number of changes to how traitlets and components work....
r2229 klass : class, str
Dav Clark
Final changes traitlet -> trait for review
r2385 The class that forms the basis for the trait. Class names
Brian Granger
A number of changes to how traitlets and components work....
r2229 can also be specified as strings, like 'foo.bar.Bar'.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 args : tuple
Positional arguments for generating the default value.
kw : dict
Keyword arguments for generating the default value.
Sylvain Corlay
doc fix
r20482 allow_none : bool [default True]
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 Indicates whether None is allowed as a value.
Thomas Kluyver
Clean up numpydoc section headers
r13587 Notes
-----
Brian Granger
Important changes to simplify traitlets....
r2182 If both ``args`` and ``kw`` are None, then the default value is None.
If ``args`` is a tuple and ``kw`` is a dict, then the default is
Jason Grout
Give subclasses of the Instance traitlet the option of overriding the klass variable to have a default klass....
r17238 created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
None, the None is replaced by ``()`` or ``{}``, respectively.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """
Jason Grout
Give subclasses of the Instance traitlet the option of overriding the klass variable to have a default klass....
r17238 if klass is None:
klass = self.klass
if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
self.klass = klass
else:
raise TraitError('The klass attribute must be a class'
' not: %r' % klass)
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
Important changes to simplify traitlets....
r2182 # self.klass is a class, so handle default_value
if args is None and kw is None:
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 default_value = None
else:
if args is None:
Brian Granger
Important changes to simplify traitlets....
r2182 # kw is not None
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 args = ()
Brian Granger
Important changes to simplify traitlets....
r2182 elif kw is None:
# args is not None
kw = {}
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 if not isinstance(kw, dict):
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError("The 'kw' argument must be a dict or None.")
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 if not isinstance(args, tuple):
Dav Clark
Final changes traitlet -> trait for review
r2385 raise TraitError("The 'args' argument must be a tuple or None.")
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
A number of changes to how traitlets and components work....
r2229 default_value = DefaultValueGenerator(*args, **kw)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
zah
Used **kwargs in initializers.
r16544 super(Instance, self).__init__(default_value, allow_none=allow_none, **metadata)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
def validate(self, obj, value):
if isinstance(value, self.klass):
return value
else:
Brian Granger
Important changes to simplify traitlets....
r2182 self.error(obj, value)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177
Brian Granger
Important changes to simplify traitlets....
r2182 def info(self):
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(self.klass, py3compat.string_types):
Brian Granger
A number of changes to how traitlets and components work....
r2229 klass = self.klass
else:
klass = self.klass.__name__
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 result = class_of(klass)
zah
Implementation in TraitType directly.
r16453 if self.allow_none:
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 return result + ' or None'
return result
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Brian Granger
A number of changes to how traitlets and components work....
r2229 self._resolve_classes()
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 super(Instance, self).instance_init()
Brian Granger
A number of changes to how traitlets and components work....
r2229
def _resolve_classes(self):
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(self.klass, py3compat.string_types):
Scott Sanderson
DEV: Support default_value in `ForwardDeclaredMixin`.
r18775 self.klass = self._resolve_string(self.klass)
Brian Granger
A number of changes to how traitlets and components work....
r2229
Brian Granger
Important changes to simplify traitlets....
r2182 def get_default_value(self):
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """Instantiate a default value instance.
Bernardo B. Marques
remove all trailling spaces
r4872
Dav Clark
Iniital stab at renames for traitlets
r2384 This is called when the containing HasTraits classes'
Brian Granger
Important changes to simplify traitlets....
r2182 :meth:`__new__` method is called to ensure that a unique instance
Dav Clark
Iniital stab at renames for traitlets
r2384 is created for each HasTraits instance.
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 """
dv = self.default_value
if isinstance(dv, DefaultValueGenerator):
Brian Granger
A number of changes to how traitlets and components work....
r2229 return dv.generate(self.klass)
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 else:
return dv
Scott Sanderson
DEV: Add ForwardDeclaredType and ForwardDeclaredInstance trait types....
r18745 class ForwardDeclaredMixin(object):
"""
Mixin for forward-declared versions of Instance and Type.
"""
Scott Sanderson
DEV: Support default_value in `ForwardDeclaredMixin`.
r18775 def _resolve_string(self, string):
Scott Sanderson
DEV: Add ForwardDeclaredType and ForwardDeclaredInstance trait types....
r18745 """
Find the specified class name by looking for it in the module in which
our this_class attribute was defined.
"""
Scott Sanderson
MAINT: Remove unncessary try/catch around import_item....
r18819 modname = self.this_class.__module__
return import_item('.'.join([modname, string]))
Scott Sanderson
DEV: Add ForwardDeclaredType and ForwardDeclaredInstance trait types....
r18745
Scott Sanderson
STY: Whitespace between class definitions.
r18746
Scott Sanderson
DEV: Add ForwardDeclaredType and ForwardDeclaredInstance trait types....
r18745 class ForwardDeclaredType(ForwardDeclaredMixin, Type):
"""
Forward-declared version of Type.
"""
pass
Scott Sanderson
STY: Whitespace between class definitions.
r18746
Scott Sanderson
DEV: Add ForwardDeclaredType and ForwardDeclaredInstance trait types....
r18745 class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
"""
Forward-declared version of Instance.
"""
pass
Scott Sanderson
STY: Whitespace between class definitions.
r18746
Dav Clark
Final changes traitlet -> trait for review
r2385 class This(ClassBasedTraitType):
"""A trait for instances of the class containing this trait.
Brian Granger
Improvements to component.py....
r2180
Brian Granger
Important changes to simplify traitlets....
r2182 Because how how and when class bodies are executed, the ``This``
Bernardo B. Marques
remove all trailling spaces
r4872 trait can only have a default value of None. This, and because we
Brian Granger
Important changes to simplify traitlets....
r2182 always validate default values, ``allow_none`` is *always* true.
"""
Brian Granger
Improvements to component.py....
r2180
Brian Granger
Important changes to simplify traitlets....
r2182 info_text = 'an instance of the same type as the receiver or None'
Brian Granger
Improvements to component.py....
r2180
Brian Granger
Important changes to simplify traitlets....
r2182 def __init__(self, **metadata):
super(This, self).__init__(None, **metadata)
Brian Granger
Improvements to component.py....
r2180
Brian Granger
Important changes to simplify traitlets....
r2182 def validate(self, obj, value):
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 # What if value is a superclass of obj.__class__? This is
# complicated if it was the superclass that defined the This
Dav Clark
Final changes traitlet -> trait for review
r2385 # trait.
Brian Granger
Fixing subtle bug in the traitlets with This....
r2183 if isinstance(value, self.this_class) or (value is None):
Brian Granger
Improvements to component.py....
r2180 return value
else:
Brian Granger
Important changes to simplify traitlets....
r2182 self.error(obj, value)
Brian Granger
Improvements to component.py....
r2180
Sylvain Corlay
A Union Traitlet
r18972 class Union(TraitType):
"""A trait type representing a Union type."""
def __init__(self, trait_types, **metadata):
"""Construct a Union trait.
This trait allows values that are allowed by at least one of the
Sylvain Corlay
early validation hook
r20518 specified trait types. A Union traitlet cannot have metadata on
its own, besides the metadata of the listed types.
Sylvain Corlay
A Union Traitlet
r18972
Parameters
----------
trait_types: sequence
The list of trait types of length at least 1.
Notes
-----
Union([Float(), Bool(), Int()]) attempts to validate the provided values
with the validation function of Float, then Bool, and finally Int.
"""
self.trait_types = trait_types
self.info_text = " or ".join([tt.info_text for tt in self.trait_types])
self.default_value = self.trait_types[0].get_default_value()
super(Union, self).__init__(**metadata)
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Sylvain Corlay
Allow for trait types like Type or Instance
r18973 for trait_type in self.trait_types:
trait_type.name = self.name
trait_type.this_class = self.this_class
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 trait_type.instance_init()
super(Union, self).instance_init()
Sylvain Corlay
Allow for trait types like Type or Instance
r18973
Sylvain Corlay
A Union Traitlet
r18972 def validate(self, obj, value):
for trait_type in self.trait_types:
try:
Sylvain Corlay
setting metadata for the union type
r20081 v = trait_type._validate(obj, value)
self._metadata = trait_type._metadata
return v
Sylvain Corlay
Overload __or__ on traitlets and add a test
r18977 except TraitError:
Sylvain Corlay
A Union Traitlet
r18972 continue
self.error(obj, value)
Sylvain Corlay
Overload __or__ on traitlets and add a test
r18977 def __or__(self, other):
if isinstance(other, Union):
return Union(self.trait_types + other.trait_types)
else:
return Union(self.trait_types + [other])
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 #-----------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 # Basic TraitTypes implementations/subclasses
Brian Granger
Added support for Type and Instance traitlets with testing.
r2177 #-----------------------------------------------------------------------------
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Dav Clark
Final changes traitlet -> trait for review
r2385 class Any(TraitType):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 default_value = None
info_text = 'any value'
zah
Implementation in TraitType directly.
r16453 class Int(TraitType):
MinRK
add Integer traitlet...
r5344 """An int trait."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
default_value = 0
MinRK
add Integer traitlet...
r5344 info_text = 'an int'
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, int):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 class CInt(Int):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A casting version of the int trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate(self, obj, value):
try:
return int(value)
except:
self.error(obj, value)
Thomas Kluyver
Various Python 3 fixes in IPython.utils
r4764 if py3compat.PY3:
Long, CLong = Int, CInt
MinRK
add Integer traitlet...
r5344 Integer = Int
Thomas Kluyver
Various Python 3 fixes in IPython.utils
r4764 else:
zah
Implementation in TraitType directly.
r16453 class Long(TraitType):
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 """A long integer trait."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Thomas Kluyver
Fix long integer literals....
r13352 default_value = 0
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 info_text = 'a long'
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, long):
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 return value
if isinstance(value, int):
return long(value)
self.error(obj, value)
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 class CLong(Long):
"""A casting version of the long integer trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 def validate(self, obj, value):
try:
return long(value)
except:
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
zah
Implementation in TraitType directly.
r16453 class Integer(TraitType):
MinRK
add Integer traitlet...
r5344 """An integer trait.
Longs that are unnecessary (<= sys.maxint) are cast to ints."""
default_value = 0
info_text = 'an integer'
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, int):
MinRK
add Integer traitlet...
r5344 return value
Pawel Jasinski
changes for ironpython
r8500 if isinstance(value, long):
MinRK
add Integer traitlet...
r5344 # downcast longs that fit in int:
# note that int(n > sys.maxint) returns a long, so
# we don't need a condition on this cast
return int(value)
Pawel Jasinski
changes for ironpython
r8500 if sys.platform == "cli":
from System import Int64
if isinstance(value, Int64):
return int(value)
MinRK
add Integer traitlet...
r5344 self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
zah
Implementation in TraitType directly.
r16453 class Float(TraitType):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A float trait."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
default_value = 0.0
info_text = 'a float'
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, float):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
if isinstance(value, int):
return float(value)
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 class CFloat(Float):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A casting version of the float trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate(self, obj, value):
try:
return float(value)
except:
self.error(obj, value)
zah
Implementation in TraitType directly.
r16453 class Complex(TraitType):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A trait for complex numbers."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
default_value = 0.0 + 0.0j
info_text = 'a complex number'
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, complex):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
if isinstance(value, (float, int)):
return complex(value)
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 class CComplex(Complex):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A casting version of the complex number trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate (self, obj, value):
try:
return complex(value)
except:
self.error(obj, value)
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 # We should always be explicit about whether we're using bytes or unicode, both
# for Python 3 conversion and for reliable unicode behaviour on Python 2. So
# we don't have a Str type.
zah
Implementation in TraitType directly.
r16453 class Bytes(TraitType):
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 """A trait for byte strings."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Thomas Kluyver
Fixes for parallel code on Python 3.
r5287 default_value = b''
Thomas Kluyver
Correct description for Bytes traitlet type...
r13429 info_text = 'a bytes object'
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, bytes):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
self.error(obj, value)
Thomas Kluyver
Arrange Str and Bytes traitlets to simplify automatic conversion to Python 3.
r4044 class CBytes(Bytes):
Thomas Kluyver
More Python 3 compatibility fixes.
r4732 """A casting version of the byte string trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate(self, obj, value):
try:
Thomas Kluyver
Arrange Str and Bytes traitlets to simplify automatic conversion to Python 3.
r4044 return bytes(value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 except:
Thomas Kluyver
CBytes and CStr only try casting to bytes (=str), not to unicode.
r4045 self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
zah
Implementation in TraitType directly.
r16453 class Unicode(TraitType):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A trait for unicode strings."""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
default_value = u''
info_text = 'a unicode string'
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, py3compat.unicode_type):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
Thomas Kluyver
Arrange Str and Bytes traitlets to simplify automatic conversion to Python 3.
r4044 if isinstance(value, bytes):
Thomas Kluyver
More informative failure when passing bytes to a Unicode traitlet
r13734 try:
return value.decode('ascii', 'strict')
except UnicodeDecodeError:
msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
raise TraitError(msg.format(value, self.name, class_of(obj)))
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 class CUnicode(Unicode):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A casting version of the unicode trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate(self, obj, value):
try:
Thomas Kluyver
Replace references to unicode and basestring
r13353 return py3compat.unicode_type(value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178 except:
self.error(obj, value)
Bernardo B. Marques
remove all trailling spaces
r4872
zah
Implementation in TraitType directly.
r16453 class ObjectName(TraitType):
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 """A string holding a valid object name in this version of Python.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 This does not check that the name exists in any scope."""
info_text = "a valid object identifier in Python"
Thomas Kluyver
Python 3 compatibility for identifiers.
r4740 if py3compat.PY3:
# Python 3:
coerce_str = staticmethod(lambda _,s: s)
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Python 3 compatibility for identifiers.
r4740 else:
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 # Python 2:
def coerce_str(self, obj, value):
"In Python 2, coerce ascii-only unicode to str"
if isinstance(value, unicode):
try:
return str(value)
except UnicodeEncodeError:
self.error(obj, value)
return value
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 def validate(self, obj, value):
value = self.coerce_str(obj, value)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
fix some string_types checks in traitlets...
r18124 if isinstance(value, string_types) and py3compat.isidentifier(value):
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 return value
self.error(obj, value)
class DottedObjectName(ObjectName):
"""A string holding a valid dotted object name in Python, such as A.b3._c"""
def validate(self, obj, value):
value = self.coerce_str(obj, value)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
fix some string_types checks in traitlets...
r18124 if isinstance(value, string_types) and py3compat.isidentifier(value, dotted=True):
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 return value
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
zah
Implementation in TraitType directly.
r16453 class Bool(TraitType):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A boolean (True, False) trait."""
Brian Granger
Minor work on kernelmanager....
r2742
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 default_value = False
info_text = 'a boolean'
def validate(self, obj, value):
zah
Implementation in TraitType directly.
r16453 if isinstance(value, bool):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 return value
self.error(obj, value)
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
class CBool(Bool):
Dav Clark
Final changes traitlet -> trait for review
r2385 """A casting version of the boolean trait."""
Brian Granger
Added casting versions of all the basic traitlet types.
r2178
def validate(self, obj, value):
try:
return bool(value)
except:
Brian Granger
More work on getting rid of ipmaker.
r2203 self.error(obj, value)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
Dav Clark
Final changes traitlet -> trait for review
r2385 class Enum(TraitType):
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 """An enum that whose value must be in a given sequence."""
Brian Granger
More work on getting rid of ipmaker.
r2203
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 def __init__(self, values, default_value=None, **metadata):
Brian Granger
More work on getting rid of ipmaker.
r2203 self.values = values
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 super(Enum, self).__init__(default_value, **metadata)
Brian Granger
More work on getting rid of ipmaker.
r2203
def validate(self, obj, value):
if value in self.values:
return value
self.error(obj, value)
def info(self):
""" Returns a description of the trait."""
result = 'any of ' + repr(self.values)
zah
Implementation in TraitType directly.
r16453 if self.allow_none:
Brian Granger
More work on getting rid of ipmaker.
r2203 return result + ' or None'
return result
class CaselessStrEnum(Enum):
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 """An enum of strings that are caseless in validate."""
Brian Granger
More work on getting rid of ipmaker.
r2203
def validate(self, obj, value):
Thomas Kluyver
Replace references to unicode and basestring
r13353 if not isinstance(value, py3compat.string_types):
Brian Granger
More work on getting rid of ipmaker.
r2203 self.error(obj, value)
for v in self.values:
if v.lower() == value.lower():
return v
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 self.error(obj, value)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 class Container(Instance):
"""An instance of a container (list, set, etc.)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 To be subclassed by overriding klass.
"""
klass = None
MinRK
allow setting Tuple traitlet with list...
r15472 _cast_types = ()
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 _valid_defaults = SequenceTypes
_trait = None
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 def __init__(self, trait=None, default_value=None, allow_none=False,
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 **metadata):
"""Create a container trait type from a list, set, or tuple.
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 The default value is created by doing ``List(default_value)``,
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 which creates a copy of the ``default_value``.
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
``trait`` can be specified, which restricts the type of elements
in the container to that TraitType.
If only one arg is given and it is not a Trait, it is taken as
``default_value``:
``c = List([1,2,3])``
Parameters
----------
trait : TraitType [ optional ]
the type for restricting the contents of the Container. If unspecified,
types are not checked.
default_value : SequenceType [ optional ]
The default value for the Trait. Must be list/tuple/set, and
will be cast to the container type.
Sylvain Corlay
doc fix
r20482 allow_none : bool [ default False ]
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 Whether to allow the value to be None
**metadata : any
further keys for extensions to the Trait (e.g. config)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 """
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 # allow List([values]):
epatters
BUG: Traitlets now accepts instantiated sub-traits in List, Tuple, etc....
r8407 if default_value is None and not is_trait(trait):
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 default_value = trait
trait = None
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 if default_value is None:
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 args = ()
elif isinstance(default_value, self._valid_defaults):
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 args = (default_value,)
Dav Clark
diff I sent to Fernando
r2380 else:
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
epatters
BUG: Traitlets now accepts instantiated sub-traits in List, Tuple, etc....
r8407 if is_trait(trait):
self._trait = trait() if isinstance(trait, type) else trait
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 self._trait.name = 'element'
elif trait is not None:
raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 super(Container,self).__init__(klass=self.klass, args=args,
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 allow_none=allow_none, **metadata)
Brian Granger
Minor work on kernelmanager....
r2742
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 def element_error(self, obj, element, validator):
e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj), validator.info(), repr_type(element))
raise TraitError(e)
Brian Granger
Minor work on kernelmanager....
r2742
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 def validate(self, obj, value):
MinRK
allow setting Tuple traitlet with list...
r15472 if isinstance(value, self._cast_types):
value = self.klass(value)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 value = super(Container, self).validate(obj, value)
if value is None:
return value
MinRK
Refactor newparallel to use Config system...
r3604
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 value = self.validate_elements(obj, value)
return value
def validate_elements(self, obj, value):
validated = []
if self._trait is None or isinstance(self._trait, Any):
return value
for v in value:
try:
zah
Fixed list validation
r16546 v = self._trait._validate(obj, v)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 except TraitError:
self.element_error(obj, v, self._trait)
else:
validated.append(v)
return self.klass(validated)
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Scott Sanderson
DEV: Forward this_class in container traits....
r18744 if isinstance(self._trait, TraitType):
self._trait.this_class = self.this_class
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 self._trait.instance_init()
super(Container, self).instance_init()
Thomas Kluyver
Merge pull request #5502 from Zaharid/iniinstance...
r16545
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
class List(Container):
"""An instance of a Python list."""
klass = list
MinRK
allow setting Tuple traitlet with list...
r15472 _cast_types = (tuple,)
MinRK
Refactor newparallel to use Config system...
r3604
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **metadata):
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 """Create a List trait type from a list, set, or tuple.
The default value is created by doing ``List(default_value)``,
MinRK
Refactor newparallel to use Config system...
r3604 which creates a copy of the ``default_value``.
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
``trait`` can be specified, which restricts the type of elements
in the container to that TraitType.
If only one arg is given and it is not a Trait, it is taken as
``default_value``:
``c = List([1,2,3])``
Parameters
----------
trait : TraitType [ optional ]
the type for restricting the contents of the Container. If unspecified,
types are not checked.
default_value : SequenceType [ optional ]
The default value for the Trait. Must be list/tuple/set, and
will be cast to the container type.
minlen : Int [ default 0 ]
The minimum length of the input list
Bradley M. Froehle
`sys.maxsize` is the maximum length of a container....
r8494 maxlen : Int [ default sys.maxsize ]
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 The maximum length of the input list
Sylvain Corlay
doc fix
r20482 allow_none : bool [ default False ]
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 Whether to allow the value to be None
**metadata : any
further keys for extensions to the Trait (e.g. config)
MinRK
Refactor newparallel to use Config system...
r3604 """
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 self._minlen = minlen
self._maxlen = maxlen
super(List, self).__init__(trait=trait, default_value=default_value,
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 **metadata)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
def length_error(self, obj, value):
e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
% (self.name, class_of(obj), self._minlen, self._maxlen, value)
raise TraitError(e)
def validate_elements(self, obj, value):
length = len(value)
if length < self._minlen or length > self._maxlen:
self.length_error(obj, value)
return super(List, self).validate_elements(obj, value)
Sylvain Corlay
simplify decorate
r20789
MinRK
allow setting Tuple traitlet with list...
r15472 def validate(self, obj, value):
value = super(List, self).validate(obj, value)
value = self.validate_elements(obj, value)
return value
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
MinRK
allow setting Tuple traitlet with list...
r15472 class Set(List):
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 """An instance of a Python set."""
klass = set
MinRK
allow setting Tuple traitlet with list...
r15472 _cast_types = (tuple, list)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
Sylvain Corlay
simplify decorate
r20789
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 class Tuple(Container):
"""An instance of a Python tuple."""
klass = tuple
MinRK
allow setting Tuple traitlet with list...
r15472 _cast_types = (list,)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
def __init__(self, *traits, **metadata):
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 """Tuple(*traits, default_value=None, **medatata)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870
Create a tuple from a list, set, or tuple.
Create a fixed-type tuple with Traits:
``t = Tuple(Int, Str, CStr)``
would be length 3, with Int,Str,CStr for each element.
If only one arg is given and it is not a Trait, it is taken as
default_value:
``t = Tuple((1,2,3))``
Otherwise, ``default_value`` *must* be specified by keyword.
Parameters
----------
*traits : TraitTypes [ optional ]
Jason Grout
fix typo in traitlet docs
r20822 the types for restricting the contents of the Tuple. If unspecified,
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 types are not checked. If specified, then each positional argument
corresponds to an element of the tuple. Tuples defined with traits
are of fixed length.
default_value : SequenceType [ optional ]
The default value for the Tuple. Must be list/tuple/set, and
will be cast to a tuple. If `traits` are specified, the
`default_value` must conform to the shape and type they specify.
Sylvain Corlay
doc fix
r20482 allow_none : bool [ default False ]
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 Whether to allow the value to be None
**metadata : any
further keys for extensions to the Trait (e.g. config)
"""
default_value = metadata.pop('default_value', None)
allow_none = metadata.pop('allow_none', True)
# allow Tuple((values,)):
epatters
BUG: Traitlets now accepts instantiated sub-traits in List, Tuple, etc....
r8407 if len(traits) == 1 and default_value is None and not is_trait(traits[0]):
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 default_value = traits[0]
traits = ()
MinRK
Refactor newparallel to use Config system...
r3604 if default_value is None:
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 args = ()
elif isinstance(default_value, self._valid_defaults):
MinRK
Refactor newparallel to use Config system...
r3604 args = (default_value,)
else:
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
self._traits = []
for trait in traits:
epatters
BUG: Traitlets now accepts instantiated sub-traits in List, Tuple, etc....
r8407 t = trait() if isinstance(trait, type) else trait
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 t.name = 'element'
self._traits.append(t)
if self._traits and default_value is None:
# don't allow default to be an empty container if length is specified
args = None
Sylvain Corlay
allow_none=False by default for Type and Instance
r20940 super(Container,self).__init__(klass=self.klass, args=args, allow_none=allow_none, **metadata)
MinRK
Refactor newparallel to use Config system...
r3604
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 def validate_elements(self, obj, value):
if not self._traits:
# nothing to validate
return value
if len(value) != len(self._traits):
e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
% (self.name, class_of(obj), len(self._traits), repr_type(value))
raise TraitError(e)
validated = []
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 for t, v in zip(self._traits, value):
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 try:
zah
Fixed tuple
r16547 v = t._validate(obj, v)
MinRK
Allow type checking on elements of List,Tuple,Set...
r3870 except TraitError:
self.element_error(obj, v, t)
else:
validated.append(v)
return tuple(validated)
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Sylvain Corlay
Resolving this_name in parameterized tuple
r20408 for trait in self._traits:
if isinstance(trait, TraitType):
trait.this_class = self.this_class
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 trait.instance_init()
super(Container, self).instance_init()
Sylvain Corlay
Resolving this_name in parameterized tuple
r20408
MinRK
Refactor newparallel to use Config system...
r3604
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 class Dict(Instance):
"""An instance of a Python dict."""
Sylvain Corlay
parameterized dict
r20766 _trait = None
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738
Sylvain Corlay
parameterized dict
r20766 def __init__(self, trait=None, default_value=NoDefaultSpecified, allow_none=False, **metadata):
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 """Create a dict trait type from a dict.
Bernardo B. Marques
remove all trailling spaces
r4872 The default value is created by doing ``dict(default_value)``,
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 which creates a copy of the ``default_value``.
Sylvain Corlay
parameterized dict
r20766
trait : TraitType [ optional ]
the type for restricting the contents of the Container. If unspecified,
types are not checked.
default_value : SequenceType [ optional ]
The default value for the Dict. Must be dict, tuple, or None, and
will be cast to a dict if not None. If `trait` is specified, the
`default_value` must conform to the constraints it specifies.
allow_none : bool [ default False ]
Whether to allow the value to be None
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 """
Sylvain Corlay
parameterized dict
r20766 if default_value is NoDefaultSpecified and trait is not None:
if not is_trait(trait):
default_value = trait
trait = None
if default_value is NoDefaultSpecified:
default_value = {}
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 if default_value is None:
Sylvain Corlay
Allow for None default value in dicts
r20308 args = None
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 elif isinstance(default_value, dict):
args = (default_value,)
elif isinstance(default_value, SequenceTypes):
args = (default_value,)
else:
raise TypeError('default value of Dict was %s' % default_value)
Sylvain Corlay
parameterized dict
r20766 if is_trait(trait):
self._trait = trait() if isinstance(trait, type) else trait
self._trait.name = 'element'
elif trait is not None:
raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
Bernardo B. Marques
remove all trailling spaces
r4872 super(Dict,self).__init__(klass=dict, args=args,
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 allow_none=allow_none, **metadata)
Brian Granger
Merge branch 'master' into kernelmanager...
r2752
Sylvain Corlay
parameterized dict
r20766 def element_error(self, obj, element, validator):
e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj), validator.info(), repr_type(element))
raise TraitError(e)
def validate(self, obj, value):
value = super(Dict, self).validate(obj, value)
if value is None:
return value
value = self.validate_elements(obj, value)
return value
def validate_elements(self, obj, value):
if self._trait is None or isinstance(self._trait, Any):
return value
validated = {}
for key in value:
v = value[key]
try:
v = self._trait._validate(obj, v)
except TraitError:
self.element_error(obj, v, self._trait)
else:
validated[key] = v
return self.klass(validated)
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 def instance_init(self):
Sylvain Corlay
Define this_class and resolve classes properly
r20768 if isinstance(self._trait, TraitType):
self._trait.this_class = self.this_class
Sylvain Corlay
adding docstring and renaming decorate into instance_init
r20790 self._trait.instance_init()
super(Dict, self).instance_init()
Sylvain Corlay
Define this_class and resolve classes properly
r20768
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560
class EventfulDict(Instance):
"""An instance of an EventfulDict."""
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 def __init__(self, default_value={}, allow_none=False, **metadata):
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560 """Create a EventfulDict trait type from a dict.
Sylvain Corlay
Allow for None default value in dicts
r20308 The default value is created by doing
``eventful.EvenfulDict(default_value)``, which creates a copy of the
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560 ``default_value``.
"""
if default_value is None:
Sylvain Corlay
Allow for None default value in dicts
r20308 args = None
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560 elif isinstance(default_value, dict):
args = (default_value,)
elif isinstance(default_value, SequenceTypes):
args = (default_value,)
else:
raise TypeError('default value of EventfulDict was %s' % default_value)
super(EventfulDict, self).__init__(klass=eventful.EventfulDict, args=args,
allow_none=allow_none, **metadata)
class EventfulList(Instance):
"""An instance of an EventfulList."""
Sylvain Corlay
allow_none=False for all trait types but Instance and Type
r20479 def __init__(self, default_value=None, allow_none=False, **metadata):
Jonathan Frederic
Add EventfulList and EventfulDict trait types.
r17560 """Create a EventfulList trait type from a dict.
The default value is created by doing
``eventful.EvenfulList(default_value)``, which creates a copy of the
``default_value``.
"""
if default_value is None:
args = ((),)
else:
args = (default_value,)
super(EventfulList, self).__init__(klass=eventful.EventfulList, args=args,
allow_none=allow_none, **metadata)
zah
Implementation in TraitType directly.
r16453 class TCPAddress(TraitType):
Brian Granger
Minor work on kernelmanager....
r2742 """A trait for an (ip, port) tuple.
This allows for both IPv4 IP addresses as well as hostnames.
"""
default_value = ('127.0.0.1', 0)
info_text = 'an (ip, port) tuple'
def validate(self, obj, value):
if isinstance(value, tuple):
if len(value) == 2:
Thomas Kluyver
Replace references to unicode and basestring
r13353 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
Brian Granger
Minor work on kernelmanager....
r2742 port = value[1]
if port >= 0 and port <= 65535:
return value
self.error(obj, value)
Bradley M. Froehle
Add traitlet for a compiled regular expression.
r6732
zah
Implementation in TraitType directly.
r16453 class CRegExp(TraitType):
Bradley M. Froehle
Improve CRegExp docstring.
r6743 """A casting compiled regular expression trait.
Accepts both strings and compiled regular expressions. The resulting
attribute will be a compiled regular expression."""
Bradley M. Froehle
Add traitlet for a compiled regular expression.
r6732
info_text = 'a regular expression'
def validate(self, obj, value):
try:
return re.compile(value)
except:
self.error(obj, value)