How to use the traitlets.TraitError function in traitlets

To help you get started, we’ve selected a few traitlets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyter / telemetry / tests / test_traits.py View on Github external
def test_mixed_handlers_values():
    handlers = [
        logging.NullHandler(),
        1
    ]
    with pytest.raises(TraitError):
        HasHandlers(
            handlers=handlers
        )
github jupyter / notebook / notebook / services / kernels / kernelmanager.py View on Github external
def _update_root_dir(self, proposal):
        """Do a bit of validation of the root dir."""
        value = proposal['value']
        if not os.path.isabs(value):
            # If we receive a non-absolute path, make it absolute.
            value = os.path.abspath(value)
        if not exists(value) or not os.path.isdir(value):
            raise TraitError("kernel root dir %r is not a directory" % value)
        return value
github jupyter / nbdime / nbdime / config.py View on Github external
def validate_elements(self, obj, value):
        value = super(IgnoreConfig, self).validate_elements(obj, value)
        for k, v in value.items():
            if not k.startswith('/'):
                raise TraitError('ignore config paths need to start with `/`')
            if not (v in (True, False) or
                    (isinstance(v, (tuple, list, set)) and
                     all(isinstance(i, string_types) for i in v)
                    )):
                raise TraitError('ignore config value needs to be True, False or a list of strings')
        return self.klass(value)
github WorldWideTelescope / pywwt / pywwt / traits.py View on Github external
def validate(self, obj, value):
        if (isinstance(value, six.string_types)
            or (isinstance(value, tuple) and len(value) == 3)):
            return to_hex(value)
        else:
            if self.from_cwo:
                raise TraitError('This attribute\'s color must be a string '
                                 '(a recognized matplotlib color name or hex '
                                 'code) or an RGB(A) tuple of 3 or 4 floats '
                                 '(3 RGB colors and, optionally, 1 opacity)')
            else:
                raise TraitError('This attribute\'s color must be a string '
                                 '(a recognized matplotlib color name or hex '
github bloomberg / bqplot / bqplot / marks.py View on Github external
def _validate_scales(self, proposal):
        """
        Validates the `scales` based on the mark's scaled attributes metadata.

        First checks for missing scale and then for 'rtype' compatibility.
        """
        # Validate scales' 'rtype' versus data attribute 'rtype' decoration
        # At this stage it is already validated that all values in self.scales
        # are instances of Scale.
        scales = proposal.value
        for name in self.trait_names(scaled=True):
            trait = self.traits()[name]
            if name not in scales:
                # Check for missing scale
                if not trait.allow_none:
                    raise TraitError("Missing scale for data attribute %s." %
                                     name)
            else:
                # Check scale range type compatibility
                if scales[name].rtype != trait.get_metadata('rtype'):
                    raise TraitError("Range type mismatch for scale %s." %
                                     name)
        return scales
github jupyter / notebook / notebook / gateway / managers.py View on Github external
def _ws_url_validate(self, proposal):
        value = proposal['value']
        # Ensure value, if present, starts with 'ws'
        if value is not None and len(value) > 0:
            if not str(value).lower().startswith('ws'):
                raise TraitError("GatewayClient ws_url must start with 'ws': '%r'" % value)
        return value
github bloomberg / bqplot / bqplot / marks.py View on Github external
def _validate_row(self, proposal):
        row = proposal.value

        if row is None:
            return row

        color = np.asarray(self.color)
        n_rows = color.shape[0]
        if len(row) != n_rows and len(row) != n_rows + 1 and len(row) != n_rows - 1:
            raise TraitError('row must be an array of size color.shape[0]')

        return row
github dask / dask-gateway / dask-gateway-server / dask_gateway_server / traitlets.py View on Github external
def validate(self, obj, 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)
            )
        return int(float(num) * self.UNIT_SUFFIXES[suffix])
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
def init_ports(self):
        if self.hub_port == self.port:
            raise TraitError("The hub and proxy cannot both listen on port %i" % self.port)
        if self.hub_port == self.proxy_api_port:
            raise TraitError("The hub and proxy API cannot both listen on port %i" % self.hub_port)
        if self.proxy_api_port == self.port:
            raise TraitError("The proxy's public and API ports cannot both be %i" % self.port)
github altair-viz / schemapi / schemapi / src / jstraitlets.py View on Github external
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__))