Python traitlets.HasTraits() Examples

The following are 30 code examples of traitlets.HasTraits(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module traitlets , or try the search function .
Example #1
Source File: test_validators.py    From traittypes with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_validaton_error():
    # Test with a squeeze coercion
    def maxlen(trait, value):
        if len(value) > 10:
            raise ValueError('Too long sequence!')
        return value

    class Foo(HasTraits):
        bar = SciType().valid(maxlen)

    # Check that it works as expected:
    foo = Foo(bar=list(range(5)))
    assert foo.bar == list(range(5))
    # Check that it fails as expected:
    with pytest.raises(TraitError):  # Should convert ValueError to TraitError
        foo.bar = list(range(10, 40))
    assert foo.bar == list(range(5))
    # Check that it can again be set correctly
    foo = Foo(bar=list(range(5, 10)))
    assert foo.bar == list(range(5, 10)) 
Example #2
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initial_values(self):
        class Foo(HasTraits):
            a = Array()
            b = Array(dtype='int')
            c = Array(None, allow_none=True)
            d = Array([])
            e = Array(Undefined)
        foo = Foo()
        self.assertTrue(np.array_equal(foo.a, np.array(0)))
        self.assertTrue(np.array_equal(foo.b, np.array(0)))
        self.assertTrue(foo.c is None)
        self.assertTrue(np.array_equal(foo.d, []))
        self.assertTrue(foo.e is Undefined) 
Example #3
Source File: test_trait_types.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def test_lowercasecard():
    from pylada.espresso.trait_types import LowerCaseString
    class LowerCase(HasTraits):
        case = LowerCaseString()
    lower = LowerCase()
    assert lower.case is None
    lower.case = "AAaa"
    assert lower.case == "aaaa" 
Example #4
Source File: test_trait_types.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def test_dimensional_with_none():
    class Dimensional(HasTraits):
        dimensional = DimensionalTrait(angstrom, allow_none=True, default_value=None)

    a = Dimensional()
    assert a.dimensional is None 
Example #5
Source File: test_trait_types.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def Dimensional():
    class Dimensional(HasTraits):
        dimensional = DimensionalTrait(angstrom, default_value=1 * bohr_radius)
    return Dimensional 
Example #6
Source File: namelists.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dictionary=None):
        from f90nml import Namelist as F90Namelist
        super(HasTraits, self).__init__()
        self.__inputs = F90Namelist()
        if dictionary is not None:
            for key, value in dictionary.items():
                setattr(self, key, value) 
Example #7
Source File: card.py    From pylada-light with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, value=None, subtitle=None):
        super(HasTraits, self).__init__()
        name = str(name).lower()
        if name not in CardNameTrait.card_names:
            CardNameTrait.card_names.add(name)
        self.name = name
        self.value = value
        self.subtitle = subtitle 
Example #8
Source File: test_traitlets.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Type_traitlet():
    class Foo(HasTraits):
        typ = Type(klass="dask_gateway_server.auth.Authenticator")

    with pytest.raises(TraitError) as exc:
        Foo(typ="dask_gateway_server.auth.not_a_real_path")
    assert "Failed to import" in str(exc.value)

    Foo(typ="dask_gateway_server.auth.SimpleAuthenticator") 
Example #9
Source File: test_traits.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_has_traits():
    """ test the has_traits func """

    class WithoutTraits(HasTraits):
        """ a traits class that has no traits """

        pass

    class WithATrait(HasTraits):
        """ a traits class that has a trait """

        my_trait = Int()

    assert not has_traits(WithoutTraits)
    assert has_traits(WithATrait) 
Example #10
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_positional_default():
    class TestCase(HasTraits):
        value = TypedTuple((1, 2, 3))

    obj = TestCase()
    assert obj.value == (1, 2, 3) 
Example #11
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_positional_trait():
    class TestCase(HasTraits):
        value = TypedTuple(Int())

    obj = TestCase(value=(1, 2, 3))
    assert obj.value == (1, 2, 3) 
Example #12
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_bad_set():
    class TestCase(HasTraits):
        value = TypedTuple(trait=Int())

    obj = TestCase()
    with nt.assert_raises(TraitError):
        obj.value = (1, 2, 'foobar') 
Example #13
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_mixed_default():
    class TestCase(HasTraits):
        value = TypedTuple(default_value=(1, 2, 'foobar'))

    obj = TestCase()
    assert obj.value == (1, 2, 'foobar') 
Example #14
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_default():
    class TestCase(HasTraits):
        value = TypedTuple(default_value=(1, 2, 3))

    obj = TestCase()
    assert obj.value == (1, 2, 3) 
Example #15
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_set_ints():
    class TestCase(HasTraits):
        value = TypedTuple(trait=Int())

    obj = TestCase()
    obj.value = (1, 2, 3)
    assert obj.value == (1, 2, 3) 
Example #16
Source File: test_traits.py    From pySINDy with MIT License 5 votes vote down vote up
def test_typed_tuple_init_ints():
    class TestCase(HasTraits):
        value = TypedTuple(trait=Int())

    obj = TestCase(value=(1, 2, 3))
    assert obj.value == (1, 2, 3) 
Example #17
Source File: dbus_utils.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
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() 
Example #18
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_array_equal(self):
        notifications = []
        class Foo(HasTraits):
            bar = Array([1, 2])
            @observe('bar')
            def _(self, change):
                notifications.append(change)
        foo = Foo()
        foo.bar = [1, 2]
        self.assertFalse(len(notifications))
        foo.bar = [1, 1]
        self.assertTrue(len(notifications)) 
Example #19
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_none(self):
        class Foo(HasTraits):
            bar = Array()
            baz = Array(allow_none=True)
        foo = Foo()
        with self.assertRaises(TraitError):
            foo.bar = None
        foo.baz = None 
Example #20
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_custom_validators(self):
        # Test with a squeeze coercion
        def squeeze(trait, value):
            if 1 in value.shape:
                value = np.squeeze(value)
            return value

        class Foo(HasTraits):
            bar = Array().valid(squeeze)

        foo = Foo(bar=[[1], [2]])
        self.assertTrue(np.array_equal(foo.bar, [1, 2]))
        foo.bar = [[1], [2], [3]]
        self.assertTrue(np.array_equal(foo.bar, [1, 2, 3]))

        # Test with a shape constraint
        def shape(*dimensions):
            def validator(trait, value):
                if value.shape != dimensions:
                    raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape))
                else:
                    return value
            return validator

        class Foo(HasTraits):
            bar = Array(np.identity(2)).valid(shape(2, 2))
        foo = Foo()
        with self.assertRaises(TraitError):
            foo.bar = [1]
        new_value = [[0, 1], [1, 0]]
        foo.bar = new_value
        self.assertTrue(np.array_equal(foo.bar, new_value)) 
Example #21
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_df_equal(self):
        notifications = []
        class Foo(HasTraits):
            bar = DataFrame([1, 2])
            @observe('bar')
            def _(self, change):
                notifications.append(change)
        foo = Foo()
        foo.bar = [1, 2]
        self.assertEqual(notifications, [])
        foo.bar = [1, 1]
        self.assertEqual(len(notifications), 1) 
Example #22
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_none(self):
        class Foo(HasTraits):
            bar = DataFrame()
            baz = DataFrame(allow_none=True)
        foo = Foo()
        with self.assertRaises(TraitError):
            foo.bar = None
        foo.baz = None 
Example #23
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_series_equal(self):
        notifications = []
        class Foo(HasTraits):
            bar = Series([1, 2])
            @observe('bar')
            def _(self, change):
                notifications.append(change)
        foo = Foo()
        foo.bar = [1, 2]
        self.assertEqual(notifications, [])
        foo.bar = [1, 1]
        self.assertEqual(len(notifications), 1) 
Example #24
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initial_values(self):
        class Foo(HasTraits):
            a = Series()
            b = Series(None, allow_none=True)
            c = Series([])
            d = Series(Undefined)
        foo = Foo()
        self.assertTrue(foo.a.equals(pd.Series()))
        self.assertTrue(foo.b is None)
        self.assertTrue(foo.c.equals(pd.Series([])))
        self.assertTrue(foo.d is Undefined) 
Example #25
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_none(self):
        class Foo(HasTraits):
            bar = Series()
            baz = Series(allow_none=True)
        foo = Foo()
        with self.assertRaises(TraitError):
            foo.bar = None
        foo.baz = None 
Example #26
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ds_equal(self):
        notifications = []
        class Foo(HasTraits):
            bar = Dataset({'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14})
            @observe('bar')
            def _(self, change):
                notifications.append(change)
        foo = Foo()
        foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14}
        self.assertEqual(notifications, [])
        foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.15}
        self.assertEqual(len(notifications), 1) 
Example #27
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_allow_none(self):
        class Foo(HasTraits):
            bar = Dataset()
            baz = Dataset(allow_none=True)
        foo = Foo()
        with self.assertRaises(TraitError):
            foo.bar = None
        foo.baz = None 
Example #28
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ds_equal(self):
        notifications = []
        class Foo(HasTraits):
            bar = DataArray([[0, 1], [2, 3]])
            @observe('bar')
            def _(self, change):
                notifications.append(change)
        foo = Foo()
        foo.bar = [[0, 1], [2, 3]]
        self.assertEqual(notifications, [])
        foo.bar = [[0, 1], [2, 4]]
        self.assertEqual(len(notifications), 1) 
Example #29
Source File: test_traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_initial_values(self):
        class Foo(HasTraits):
            b = DataArray(None, allow_none=True)
            c = DataArray([])
            d = DataArray(Undefined)
        foo = Foo()
        self.assertTrue(foo.b is None)
        self.assertTrue(foo.c.equals(xr.DataArray([])))
        self.assertTrue(foo.d is Undefined) 
Example #30
Source File: test_validators.py    From traittypes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_coercion_validator():
    # Test with a squeeze coercion
    def truncate(trait, value):
        return value[:10]

    class Foo(HasTraits):
        bar = SciType().valid(truncate)

    foo = Foo(bar=list(range(20)))
    assert foo.bar == list(range(10))
    foo.bar = list(range(10, 40))
    assert foo.bar == list(range(10, 20))