我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用traitlets.HasTraits()。
def __init__(self, obj, interface_name, exclude=None): self._interface_name = interface_name self._obj = obj self._ro_props = OrderedDict() self._rw_props = OrderedDict() self._methods = [] self._signals = [] self._exclude = exclude if isinstance(obj, HasTraits): self._parse_traits()
def test_ctor_without_default_value(self): # -- IMPLICIT: default_value = Color.red (first enum-value) class Example2(HasTraits): color = UseEnum(Color) example = Example2() self.assertEqual(example.color, Color.red)
def test_ctor_with_default_value_as_enum_value(self): # -- CONVERT: number => Enum value (item) class Example2(HasTraits): color = UseEnum(Color, default_value=Color.green) example = Example2() self.assertEqual(example.color, Color.green)
def test_ctor_with_default_value_none_and_not_allow_none(self): # -- IMPLICIT: default_value = Color.red (first enum-value) class Example2(HasTraits): color1 = UseEnum(Color, default_value=None, allow_none=False) color2 = UseEnum(Color, default_value=None) example = Example2() self.assertEqual(example.color1, Color.red) self.assertEqual(example.color2, Color.red)
def test_ctor_with_default_value_none_and_allow_none(self): class Example2(HasTraits): color1 = UseEnum(Color, default_value=None, allow_none=True) color2 = UseEnum(Color, allow_none=True) example = Example2() self.assertIs(example.color1, None) self.assertIs(example.color2, None)
def test_assign_none_without_allow_none_resets_to_default_value(self): class Example2(HasTraits): color1 = UseEnum(Color, allow_none=False) color2 = UseEnum(Color) example = Example2() example.color1 = None example.color2 = None self.assertIs(example.color1, Color.red) self.assertIs(example.color2, Color.red)
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 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)
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)