def AnonymousMapping(**traits):
"""Create an anonymous HasTraits mapping
This is used when a JSONSchema defines an object inline, rather than in
a separate statement
Example
-------
>>> Foo = AnonymousMapping(val=T.Integer())
>>> f = Foo(val=4)
>>> type(f)
<class 'traitlets.traitlets.AnonymousMapping'>
"""
return T.MetaHasTraits('AnonymousMapping', (JSONHasTraits,), traits)
python类Integer()的实例源码
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})