Python attr.name() Examples

The following are 12 code examples of attr.name(). 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 attr , or try the search function .
Example #1
Source File: validators.py    From grafanalib with Apache License 2.0 6 votes vote down vote up
def is_color_code(instance, attribute, value):
    """
    A validator that raises a :exc:`ValueError` if attribute value
    is not valid color code.
    Value considered as valid color code if it starts with # char
    followed by hexadecimal.
    """
    err = "{attr} should be a valid color code".format(attr=attribute.name)
    if not value.startswith("#"):
        raise ValueError(err)
    if len(value) != 7:
        raise ValueError(err)
    try:
        int(value[1:], 16)
    except ValueError:
        raise ValueError(err) 
Example #2
Source File: validators.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__(self, inst, attr, value):
        out_lower = self.bounds[0] is not None and (
            value < self.bounds[0] if self.closed[0] else value <= self.bounds[0]
        )
        out_upper = self.bounds[1] is not None and (
            value > self.bounds[1] if self.closed[1] else value >= self.bounds[1]
        )

        if np.any(out_lower) or np.any(out_upper):
            common_msg = f"out of bounds {self.bounds_str}"

            if np.isscalar(value):
                msg = f"Value {value} of variable '{attr.name}' is " + common_msg
            else:
                msg = f"Found value(s) in array '{attr.name}' " + common_msg

            raise ValueError(msg) 
Example #3
Source File: engine_step.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _asdict(self):
    ret = thaw(attr.asdict(self, filter=(lambda attr, val: (
      (val and val != attr.default or (attr.name in self._RENDER_WHITELIST)) and
      attr.name not in self._RENDER_BLACKLIST
    ))))
    if self.env_prefixes.mapping:
      ret['env_prefixes'] = dict(self.env_prefixes.mapping)
    if self.env_suffixes.mapping:
      ret['env_suffixes'] = dict(self.env_suffixes.mapping)
    return ret 
Example #4
Source File: validators.py    From grafanalib with Apache License 2.0 5 votes vote down vote up
def __call__(self, inst, attr, value):
        if value not in self.choices:
            raise ValueError("{attr} should be one of {choice}".format(
                attr=attr.name, choice=self.choices)) 
Example #5
Source File: validators.py    From grafanalib with Apache License 2.0 5 votes vote down vote up
def __call__(self, inst, attr, value):
        if False in set(map(lambda el: isinstance(el, self.etype), value)):
            raise ValueError("{attr} should be list of {etype}".format(
                attr=attr.name, etype=self.etype)) 
Example #6
Source File: test_container.py    From attrs-strict with Apache License 2.0 5 votes vote down vote up
def test_container_is_not_of_expected_type_raises_TypeError(
    items, types, message
):
    validator = type_validator()

    attr = MagicMock()
    attr.name = "Smth"
    attr.type = types

    with pytest.raises(ValueError) as error:
        validator(None, attr, items)

    repr_msg = "<{}>".format(message)
    assert repr_msg == repr(error.value) 
Example #7
Source File: test_container.py    From attrs-strict with Apache License 2.0 5 votes vote down vote up
def test_raises_when_container_is_empty_and_empty_ok_is_false():
    # GIVEN
    items = []
    validator = type_validator(empty_ok=False)
    attr = MagicMock()
    attr.name = "Smth"
    attr.type = str

    # WHEN
    with pytest.raises(ValueError) as error:
        validator(None, attr, items)

    # THEN
    assert "Smth can not be empty and must be str"
    "(got None)" == str(error.value) 
Example #8
Source File: _version.py    From parver with MIT License 5 votes vote down vote up
def not_bool(inst, attr, value):
    if isinstance(value, bool):
        raise TypeError(
            "'{name}' must not be a bool (got {value!r})"
            .format(name=attr.name, value=value)
        ) 
Example #9
Source File: _version.py    From parver with MIT License 5 votes vote down vote up
def is_non_negative(inst, attr, value):
    if value < 0:
        raise ValueError(
            "'{name}' must be non-negative (got {value!r})"
            .format(name=attr.name, value=value)
        ) 
Example #10
Source File: _version.py    From parver with MIT License 5 votes vote down vote up
def sequence_of(validator, allow_empty=False):
    if isinstance(validator, list):
        validator = and_(*validator)

    def validate(inst, attr, value):
        is_seq(inst, attr, value)

        if not allow_empty and not value:
            raise ValueError(
                "'{name}' cannot be empty".format(name=attr.name, value=value)
            )

        for i, item in enumerate(value):
            try:
                validator(inst, attr, item)
            except (ValueError, TypeError):
                # now that we know it's invalid, let's re-do the validation
                # with a better attribute name. Since we have to copy data,
                # we only do it when we know we have to raise an exception.
                item_attr = copy.copy(attr)
                object.__setattr__(item_attr, 'name', '{}[{}]'.format(attr.name, i))
                try:
                    validator(inst, item_attr, item)
                except Exception as exc:
                    six.raise_from(exc, None)
                else:
                    # if we somehow got here, raise original exception
                    raise

    return validate 
Example #11
Source File: validators.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, inst, attr, value):
        if not np.issubdtype(value.dtype, self.dtype):
            raise TypeError(
                f"'{attr.name}' array has {value.dtype!r}, which is not "
                f"a sub-dtype of {self.dtype!r}"
            ) 
Example #12
Source File: engine_step.py    From recipes-py with Apache License 2.0 4 votes vote down vote up
def __attrs_post_init__(self):
    object.__setattr__(self, 'cmd', tuple(self.cmd))

    # if cmd is empty, then remove all values except for the few that actually
    # apply with a null command.
    if not self.cmd:
      _keep_fields = ('name', 'cmd')
      for attrib in attr.fields(self.__class__):
        if attrib.name in _keep_fields:
          continue
        # cribbed from attr/_make.py; the goal is to compute the attribute's
        # default value.
        if isinstance(attrib.default, attr.Factory):
          if attrib.default.takes_self:
            val = attrib.default.factory(self)
          else:
            val = attrib.default.factory()
        else:
          val = attrib.default
        if attrib.converter:
          val = attrib.converter(val)
        object.__setattr__(self, attrib.name, val)
      object.__setattr__(self, 'cost', None)
      return

    if self.ok_ret is not self.ALL_OK:
      object.__setattr__(self, 'ok_ret', frozenset(self.ok_ret))
    object.__setattr__(self, 'env', freeze(self.env))

    # Ensure that output placeholders don't have ambiguously overlapping names.
    placeholders = set()
    collisions = set()
    ns_str = None
    for itm in self.cmd:
      if isinstance(itm, OutputPlaceholder):
        key = itm.namespaces, itm.name
        if key in placeholders:
          ns_str = '.'.join(itm.namespaces)
          if itm.name is None:
            collisions.add("{} unnamed".format(ns_str))
          else:
            collisions.add("{} named {!r}".format(ns_str, itm.name))
        else:
          placeholders.add(key)

    if collisions:
      raise ValueError(
          'Found conflicting Placeholders: {!r}. Please give these placeholders'
          ' unique "name"s and access them like `step_result.{}s[name]`.'
          .format(list(collisions), ns_str))


  # Used with to indicate that all retcodes values are acceptable.