Python traitlets 模块,TraitError() 实例源码
我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用traitlets.TraitError()。
def render_string(self):
height = '%spx' % min(self._string.count('\n') * 16 + 36, 600)
try:
self.textarea = ipy.Textarea(self._string[:self.CHUNK],
layout=Layout(width='100%', height=height))
except traitlets.TraitError:
self.textarea = ipy.Textarea('[NOT SHOWN - UNABLE TO DECODE FILE]',
layout=Layout(height='300px',
**self.TEXTAREA_KWARGS))
return
finally:
self.children = [self.textarea]
self._current_pos = self.CHUNK
if len(self._string) > self.CHUNK:
self.textarea.value += self.TRUNCATE_MESSAGE
self.load_more_button = ipy.Button(description='See more')
self.load_more_button.on_click(self.load_more)
self.children = self.children + (self.load_more_button,)
def validate(self, obj, value):
"""
Validate that the passed in value is a valid memory specification
It could either be a pure int, when it is taken as a byte value.
If it has one of the suffixes, it is converted into the appropriate
pure byte value.
"""
if isinstance(value, (int, float)):
return int(value)
try:
num = float(value[:-1])
except ValueError:
raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
suffix = value[-1]
if suffix not in self.UNIT_SUFFIXES:
raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
else:
return int(float(num) * self.UNIT_SUFFIXES[suffix])
def __init__(self, **kwargs):
# make a copy of the _metadata so we can modify locally
self._metadata = self._metadata.copy()
# Add default traits if needed
default = self._get_additional_traits()
# TODO: protect against overwriting class attributes defined above.
# perhaps use double underscores?
if default:
all_traits = self.traits()
self.add_traits(**{key: default for key in kwargs
if key not in all_traits})
# Validate keywords to make sure they are valid traits
all_traits = list(self.traits())
for k in kwargs:
if k not in all_traits:
raise T.TraitError("Invalid trait: {0}. Options for "
"this class: {1}".format(k, all_traits))
super(JSONHasTraits, self).__init__(**kwargs)
def __init__(self, *args, **kwargs):
classes = list(self._class_defs())
if len(classes) == 0 or self.__class__ in self._class_defs():
return super(AnyOfObject, self).__init__(*args, **kwargs)
for cls in self._class_defs():
# TODO: add a second pass where we allow additional properties?
if all(key in cls.class_traits() for key in kwargs):
try:
cls(*args, **kwargs)
except (T.TraitError, ValueError):
pass
else:
assert issubclass(cls, JSONHasTraits)
self.__class__ = cls
return super(JSONHasTraits, self).__init__(*args, **kwargs)
raise T.TraitError("{cls}: initialization arguments not "
"valid in any wrapped classes"
"".format(cls=self.__class__.__name__))
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
# Should validate against only one of the trait types
valid_count = 0
with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
except T.TraitError:
continue
valid_count += 1
if valid_count == 1:
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, '_' + self.name + '_metadata',
trait_type.metadata)
return v
self.error(obj, value)
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
try:
self.not_this.validate(obj, value)
except T.TraitError:
return value
else:
self.error(obj, value)
##########################################################################
# Visitor Pattern
#
# This implements to_dict() and from_dict() using an External Visitor Pattern
# built for the above classes.
def clsvisit_JSONHasTraits(self, cls, dct, *args, **kwargs):
try:
obj = cls()
except TypeError: # Argument missing
obj = cls('')
additional_traits = cls._get_additional_traits()
# Extract all other items, assigning to appropriate trait
reverse_name_map = {v:k for k, v in obj._trait_name_map.items()}
for schema_key, val in dct.items():
if schema_key in obj._metadata:
obj._metadata[schema_key] = val
else:
trait_key = reverse_name_map.get(schema_key, schema_key)
subtrait = obj.traits().get(trait_key, additional_traits)
if not subtrait:
raise T.TraitError("trait {0} not valid in class {1}"
"".format(trait_key, cls))
obj.set_trait(trait_key,
self.visit(subtrait, val, *args, **kwargs))
return obj
def test_hastraits_required():
class Foo(jst.JSONHasTraits):
_required_traits = ['name']
name = jst.JSONString()
age = jst.JSONNumber()
f1 = Foo(name="Sue", age=32)
f2 = Foo(age=32)
# contains all required pieces
f1.to_dict()
with pytest.raises(T.TraitError) as err:
f2.to_dict()
assert err.match("Required trait 'name' is undefined")
def test_AnyOfObject_subclasses():
class FooBar(jst.AnyOfObject):
pass
class Foo(FooBar):
bar = jst.JSONString()
class Bar(FooBar):
bar = jst.JSONNumber()
with pytest.raises(T.TraitError):
FooBar(bar=None)
with pytest.raises(T.TraitError):
FooBar(num=16)
assert FooBar(bar='hello').__class__ == Foo
assert FooBar(bar='blah').bar == 'blah'
assert FooBar(bar=14).__class__ == Bar
assert FooBar(bar=42).bar == 42
def test_to_python():
class Foo(jst.JSONHasTraits):
_required_traits = ['a', 'b']
a = jst.JSONNumber()
b = jst.JSONString()
class Bar(jst.JSONHasTraits):
c = jst.JSONArray(jst.JSONNumber())
d = jst.JSONInstance(Foo)
e = jst.JSONArray(jst.JSONInstance(Foo))
D = {'c': [1, 2, 3], 'd': {'a': 5, 'b': 'blah'},
'e': [{'a': 3, 'b': 'foo'}, {'a': 4, 'b': 'bar'}]}
obj = Bar.from_dict(D)
obj2 = eval(obj.to_python())
assert obj2.to_dict() == obj.to_dict() == D
# Make sure there is an error if required traits are missing
foo = Foo(a=4)
with pytest.raises(T.TraitError):
foo.to_python()
def test_assign_enum_value__with_other_enum_raises_error(self):
example = self.Example()
with self.assertRaises(TraitError):
example.color = OtherColor.green
def test_assign_bad_enum_value_name__raises_error(self):
# -- CONVERT: string => Enum value (item)
bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
for value in bad_enum_names:
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_enum_value_number__raises_error(self):
# -- CONVERT: number => Enum value (item)
bad_numbers = [-1, 0, 5]
for value in bad_numbers:
self.assertIsInstance(value, int)
assert UseEnum(Color).select_by_number(value, None) is None
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_value_with_to_enum_or_none(self):
class Example2(HasTraits):
color = UseEnum(Color, allow_none=True)
example = Example2()
with self.assertRaises(TraitError):
example.color = "BAD_VALUE"
def docker_build_host_validate(self, proposal):
parts = urlparse(proposal.value)
if parts.scheme != 'unix' or parts.netloc != '':
raise TraitError("Only unix domain sockets on same node are supported for build_docker_host")
return proposal.value
def test_assign_enum_value__with_other_enum_raises_error(self):
example = self.Example()
with self.assertRaises(TraitError):
example.color = OtherColor.green
def test_assign_bad_enum_value_name__raises_error(self):
# -- CONVERT: string => Enum value (item)
bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
for value in bad_enum_names:
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_enum_value_number__raises_error(self):
# -- CONVERT: number => Enum value (item)
bad_numbers = [-1, 0, 5]
for value in bad_numbers:
self.assertIsInstance(value, int)
assert UseEnum(Color).select_by_number(value, None) is None
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_value_with_to_enum_or_none(self):
class Example2(HasTraits):
color = UseEnum(Color, allow_none=True)
example = Example2()
with self.assertRaises(TraitError):
example.color = "BAD_VALUE"
def _validate_current(self, proposal):
if proposal.value not in self.values:
raise TraitError("Current value not part of the values.")
return proposal.value
def _urlpath_validate(self, proposal):
if proposal['value'].endswith('/'):
raise TraitError("urlpath cannot end with a /")
return proposal['value']
def test_shape_validator():
trait = None
value = Mock()
correct = (1, 1)
validator = shape_validator(*correct)
value.shape = correct
assert validator(trait, value).shape == value.shape
incorrect = (1, 2)
value.shape = incorrect
pytest.raises(traitlets.TraitError, validator, trait, value)
def test_length_validator():
trait = None
value = np.array((1.0, 1.0))
lengths = np.sqrt(2), 1.0
validator = length_validator(*lengths)
assert np.allclose(validator(trait, value), value)
value = np.array((0.0, 0.0))
pytest.raises(traitlets.TraitError, validator, trait, value)
def test_error(self):
s = R.Stitch('')
assert s.error == 'continue'
s.error = 'raise'
assert s.error == 'raise'
with pytest.raises(TraitError):
s.error = 'foo'
def test_testcases_traitlets(testcase):
testcase = testcases[testcase]
modulename = '_schema'
schema = testcase['schema']
valid = testcase.get('valid', [])
invalid = testcase.get('invalid', [])
traitlets_obj = JSONSchema(schema)
for key, code in traitlets_obj.source_tree().items():
if key in ['jstraitlets.py', 'tests']:
continue
# Print code here... useful for debugging when errors happen
print(70 * '#')
print(code)
print()
schema = traitlets_obj.load_module(modulename, reload_module=True)
for instance in valid:
schema.Root.from_dict(instance)
for instance in invalid:
with pytest.raises(T.TraitError):
r = schema.Root.from_dict(instance)
r.to_dict() # catches unfilled requirements
def _validate_numeric(trait, obj, value,
minimum=undefined, maximum=undefined,
exclusiveMinimum=undefined, exclusiveMaximum=undefined,
multipleOf=undefined, **extra_kwds):
if value is None:
return value
if minimum is not undefined:
exclusive = exclusiveMinimum is not undefined and exclusiveMinimum
if value < minimum or (exclusive and value == minimum):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"not be less than {min_bound}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, min_bound=minimum))
if maximum is not undefined:
exclusive = exclusiveMaximum is not undefined and exclusiveMaximum
if value > maximum or (exclusive and value == maximum):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"not be greater than {max_bound}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, max_bound=maximum))
if multipleOf is not undefined:
if value % multipleOf != 0:
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"be a multiple of {multiple}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, multiple=multipleOf))
return value
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
value = super(JSONArray, self).validate(obj, value)
if self.uniqueItems and not _has_unique_elements(value):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"have unique elements".format(
name=self.name, klass=class_of(obj)))
return value
# Need to bypass the dynamic default in T.Container() in the case that
# the trait is undefined
def generic_visit(self, trait, dct, *args, **kwargs):
if dct is None or dct is undefined:
return dct
if isinstance(dct, (six.integer_types, six.string_types, bool, float)):
return dct
else:
raise T.TraitError('cannot set {0} to {1}'.format(trait, dct))
def visit_Union(self, trait, dct, *args, **kwargs):
try:
return self.generic_visit(trait, dct)
except T.TraitError:
for subtrait in trait.trait_types:
try:
return self.visit(subtrait, dct)
except T.TraitError:
pass
raise # no valid trait found
def clsvisit_AnyOfObject(self, trait, dct, *args, **kwargs):
# TODO: match additional_traits as well?
for subcls in trait._class_defs():
if all(key in subcls.class_traits() for key in dct):
try:
obj = self.clsvisit(subcls, dct)
except (T.TraitError, ValueError):
pass
else:
return trait(**{name: getattr(obj, name)
for name in obj.trait_names()})
else:
raise T.TraitError("{cls}: dict representation not "
"valid in any wrapped classes"
"".format(cls=trait.__name__))
def test_traits(trait, failcases, passcases):
obj = T.HasTraits() # needed to pass to validate()
for passcase in passcases:
trait._validate(obj, passcase)
for failcase in failcases:
with pytest.raises(T.TraitError):
trait._validate(obj, failcase)
def test_hastraits_defaults():
class Foo(jst.JSONHasTraits):
_additional_traits = [T.Integer()]
name = T.Unicode()
f = Foo(name="Bob", age=40)
f.set_trait('year', 2000)
assert set(f.trait_names()) == {'name', 'age', 'year'}
with pytest.raises(T.TraitError):
f.set_trait('foo', 'abc')
with pytest.raises(T.TraitError):
f.set_trait('age', 'blah')
def test_AnyOfObject():
class Foo(jst.JSONHasTraits):
intval = T.Integer()
flag = T.Bool()
class Bar(jst.JSONHasTraits):
strval = T.Unicode()
flag = T.Bool()
class FooBar(jst.AnyOfObject):
_classes = [Foo, Bar]
FooBar(strval='hello', flag=True)
FooBar(intval=5, flag=True)
with pytest.raises(T.TraitError):
FooBar(strval=666, flag=False)
with pytest.raises(T.TraitError):
FooBar(strval='hello', flag='bad arg')
with pytest.raises(T.TraitError):
FooBar(intval='bad arg', flag=False)
with pytest.raises(T.TraitError):
FooBar(intval=42, flag='bad arg')
# Test from_dict
FooBar.from_dict({'strval': 'hello', 'flag': True})
FooBar.from_dict({'intval': 42, 'flag': False})
def test_to_from_dict_with_defaults():
dct = {'x': 4, 'y': {'val': 'hello', 'other_val': 'hello 2'}}
obj = Foo.from_dict(dct)
dct2 = obj.to_dict()
assert dct == dct2
dct = {'x': 4, 'z': 'blah', 'y': {'val': 'hello'}}
with pytest.raises(T.TraitError):
Foo.from_dict(dct)
def test_assign_enum_value__with_other_enum_raises_error(self):
example = self.Example()
with self.assertRaises(TraitError):
example.color = OtherColor.green
def test_assign_bad_enum_value_name__raises_error(self):
# -- CONVERT: string => Enum value (item)
bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
for value in bad_enum_names:
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_enum_value_number__raises_error(self):
# -- CONVERT: number => Enum value (item)
bad_numbers = [-1, 0, 5]
for value in bad_numbers:
self.assertIsInstance(value, int)
assert UseEnum(Color).select_by_number(value, None) is None
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_value_with_to_enum_or_none(self):
class Example2(HasTraits):
color = UseEnum(Color, allow_none=True)
example = Example2()
with self.assertRaises(TraitError):
example.color = "BAD_VALUE"
def _validate_max_length(self, proposal):
if not len(proposal['value']) == self._npoints:
raise t.TraitError(
'len({class_name}().{trait_name}) must be equal to {class_name}().nsegments + 1. Proposed {trait_name} is {proposal}'.format(
class_name=proposal['owner'].__class__.__name__,
trait_name=proposal['trait'].name,
proposal=proposal['value']
)
)
return proposal['value']
def _less_than_maximum_real_power_check(self, proposal):
if not proposal['value'] <= self.maximum_real_power:
raise t.TraitError(
'{class_name}().{trait_name} must be a less than or equal to {class_name}().maximum_real_power.'.format(
class_name=proposal['owner'].__class__.__name__,
trait_name=proposal['trait'].name
)
)
else:
return proposal['value']
def test_required_keyword():
schema = {
'type': 'object',
'definitions': {
'positiveInteger': {'type': 'integer', 'minimum': 0},
'twoNumbers': {'properties': {'num1': {'type': 'number'},
'num2': {'type': 'number'}}}
},
'properties': {
'string1': {'type': 'string'},
'string2': {'type': 'string'},
'integer1': {'type': 'integer'},
'integer2': {'type': 'integer'},
'number1': {'type': 'number'},
'number2': {'type': 'number'},
'bool1': {'type': 'boolean'},
'bool2': {'type': 'boolean'},
'null1': {'type': 'null'},
'null2': {'type': 'null'},
'enum1': {'enum': [1, 2, 3]},
'enum2': {'enum': [1, 2, 3]},
'array1': {'type': 'array', 'items': {'type': 'integer'}},
'array2': {'type': 'array', 'items': {'type': 'integer'}},
'traitref1': {'$ref': '#/definitions/positiveInteger'},
'traitref2': {'$ref': '#/definitions/positiveInteger'},
'objref1': {'$ref': '#/definitions/twoNumbers'},
'objref2': {'$ref': '#/definitions/twoNumbers'},
'typelist1': {'type': ['string', 'integer']},
'typelist2': {'type': ['string', 'integer']},
},
'required': ['string1', 'integer1', 'number1',
'bool1', 'null1', 'enum1', 'array1',
'traitref1', 'objref1', 'typelist1']
}
js = JSONSchema(schema).traitlets
js.load_module('_schema', reload_module=True)
from _schema import Root
assert Root()._required_traits == js.required
r = Root()
with pytest.raises(T.TraitError) as err:
r.to_dict()
assert err.match("Required trait '[a-z]+1' is undefined")
def test_default_generator(default_generator):
g = default_generator
assert g.name == 'GenCo1'
assert g.generator_bus == 'Bus1'
assert g.generation_type == 'NATURALGAS'
assert g.maximum_real_power == 100
assert g.ramp_up_rate == 100
assert g.ramp_down_rate == 100
assert len(g.cost_curve_points) == 4
assert len(g.cost_curve_values) == 4
with pt.raises(T.TraitError):
g.ramp_up_rate = 100.5
with pt.raises(T.TraitError):
g.ramp_down_rate = 100.5
assert g.ramp_up_rate == 100
assert g.ramp_down_rate == 100
with pt.raises(AttributeError) as excinfo:
g.ramp_rate
assert 'ramp_down_rate' in str(excinfo.value) and 'ramp_up_rate' in str(excinfo.value)
with pt.raises(T.TraitError):
g.nsegments = 0
with pt.raises(T.TraitError):
g.initial_real_power = 100.5
with pt.raises(T.TraitError):
g.initial_imag_power = 100.5
with pt.raises(T.TraitError) as excinfo:
g.cost_curve_points = [0, 1, 2]
assert 'must be equal to' in str(excinfo.value)
with pt.raises(T.TraitError) as excinfo:
g.cost_curve_values = [0, 1, 2]
assert 'must be equal to' in str(excinfo.value)