Python attr.NOTHING Examples

The following are 30 code examples of attr.NOTHING(). 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: fields.py    From related with MIT License 7 votes vote down vote up
def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
               key=None):
    """
    Create new str field on a model.

    :param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
    :param default: any string value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, string_types,
                                            validators.regex(regex))
    return attrib(default=default, converter=converters.str_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #2
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
               key=None):
    """
    Create new child field on a model.

    :param cls: class (or name) of the model to be related.
    :param default: any object value of type cls
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    converter = converters.to_child_field(cls)
    validator = _init_fields.init_validator(
        required, object if isinstance(cls, str) else cls
    )
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, cmp=cmp, metadata=dict(key=key)) 
Example #3
Source File: __init__.py    From cattrs with MIT License 6 votes vote down vote up
def _create_hyp_class(attrs_and_strategy):
    """
    A helper function for Hypothesis to generate attrs classes.

    The result is a tuple: an attrs class, and a tuple of values to
    instantiate it.
    """

    def key(t):
        return t[0].default is not attr.NOTHING

    attrs_and_strat = sorted(attrs_and_strategy, key=key)
    attrs = [a[0] for a in attrs_and_strat]
    for i, a in enumerate(attrs):
        a.counter = i
    vals = tuple((a[1]) for a in attrs_and_strat)
    return tuples(
        just(
            make_class("HypClass", OrderedDict(zip(gen_attr_names(), attrs)))
        ),
        tuples(*vals),
    ) 
Example #4
Source File: test_structure_attrs.py    From cattrs with MIT License 6 votes vote down vote up
def test_structure_simple_from_dict_default(converter, cl_and_vals, data):
    """Test structuring non-nested attrs classes with default value."""
    cl, vals = cl_and_vals
    obj = cl(*vals)
    attrs_with_defaults = [a for a in fields(cl) if a.default is not NOTHING]
    to_remove = data.draw(
        lists(elements=sampled_from(attrs_with_defaults), unique=True)
    )

    for a in to_remove:
        if isinstance(a.default, Factory):
            setattr(obj, a.name, a.default.factory())
        else:
            setattr(obj, a.name, a.default)

    dumped = asdict(obj)

    for a in to_remove:
        del dumped[a.name]

    assert obj == converter.structure(dumped, cl) 
Example #5
Source File: __init__.py    From cattrs with MIT License 6 votes vote down vote up
def _create_hyp_class(attrs_and_strategy):
    """
    A helper function for Hypothesis to generate attrs classes.

    The result is a tuple: an attrs class, and a tuple of values to
    instantiate it.
    """

    def key(t):
        return t[0].default is not NOTHING

    attrs_and_strat = sorted(attrs_and_strategy, key=key)
    attrs = [a[0] for a in attrs_and_strat]
    for i, a in enumerate(attrs):
        a.counter = i
    vals = tuple((a[1]) for a in attrs_and_strat)
    return st.tuples(
        st.just(
            make_class("HypClass", OrderedDict(zip(gen_attr_names(), attrs)))
        ),
        st.tuples(*vals),
    ) 
Example #6
Source File: secrets.py    From environ-config with Apache License 2.0 6 votes vote down vote up
def _get(self, environ, metadata, prefix, name):
        ce = metadata[CNF_KEY]

        if ce.name is not None:
            var = ce.name
        else:
            if callable(self.vault_prefix):
                vp = self.vault_prefix(environ)
            else:
                vp = self.vault_prefix
            var = "_".join(((vp,) + prefix + (name,))).upper()

        log.debug("looking for env var '%s'." % (var,))
        val = environ.get(
            var,
            (
                attr.NOTHING
                if isinstance(ce.default, attr.Factory)
                else ce.default
            ),
        )
        if val is RAISE:
            raise MissingSecretError(var)
        return _SecretStr(val) 
Example #7
Source File: secrets.py    From environ-config with Apache License 2.0 6 votes vote down vote up
def _get(self, environ, metadata, prefix, name):
        # Delayed loading.
        if self._cfg is None and self._env_name is not None:
            log.debug("looking for env var '%s'." % (self._env_name,))
            self._cfg = _load_ini(
                environ.get(self._env_name, self._env_default)
            )

        ce = metadata[CNF_KEY]
        ic = metadata[CNF_INI_SECRET_KEY]
        section = ic.section

        if ce.name is not None:
            var = ce.name
        else:
            var = "_".join((prefix + (name,)))
        try:
            log.debug("looking for '%s' in section '%s'." % (var, section))
            return _SecretStr(self._cfg.get(section, var))
        except NoOptionError:
            if isinstance(ce.default, attr.Factory):
                return attr.NOTHING
            elif ce.default is not RAISE:
                return ce.default
            raise MissingSecretError(var) 
Example #8
Source File: attrs.py    From marshmallow-annotations with MIT License 6 votes vote down vote up
def _preprocess_typehint(self, typehint, kwargs, field_name, target):
        # while this seems contradictory to this converter, we need to
        # ignore attrs specific actions when a container type, e.g. a List[T],
        # contains a non-attrs manufactured type because this is recursively
        # called during schema generation.
        # however those types will still require an entry in the registry
        # is handled outside this converter
        if not _is_attrs(target):
            return

        attr = _get_attr_from_attrs(target.__attrs_attrs__, field_name)

        if attr.default != NOTHING:
            # default to optional even if the typehint isn't
            # but don't override the user saying otherwise
            kwargs.setdefault("required", False)
            kwargs.setdefault("missing", missing) 
Example #9
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
                 key=None):
    """
    Create new decimal field on a model.

    :param default: any decimal value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, Decimal)
    return attrib(default=default, converter=lambda x: Decimal(x),
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #10
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def UUIDField(default=NOTHING, required=False, repr=True, cmp=True, key=None):
    """
    Create new UUID field on a model.

    :param default: any value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    cls = UUID
    default = _init_fields.init_default(required, default, uuid4)
    validator = _init_fields.init_validator(required, cls)
    return attrib(default=default, converter=converters.str_to_uuid,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #11
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
    """
    Create new set field on a model.

    :param cls: class (or name) of the model to be related in Set.
    :param default: any TypedSet or set
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, set())
    converter = converters.to_set_field(cls)
    validator = _init_fields.init_validator(required, types.TypedSet)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, metadata=dict(key=key)) 
Example #12
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
    """
    Create new sequence field on a model.

    :param cls: class (or name) of the model to be related in Sequence.
    :param default: any TypedSequence or list
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, [])
    converter = converters.to_sequence_field(cls)
    validator = _init_fields.init_validator(required, types.TypedSequence)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, metadata=dict(key=key)) 
Example #13
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def URLField(default=NOTHING, required=True, repr=True, cmp=True, key=None):
    """
    Create new UUID field on a model.

    :param default: any value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    cls = ParseResult
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, cls)
    return attrib(default=default, converter=converters.str_to_url,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #14
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
                 key=None):
    """
    Create new mapping field on a model.

    :param cls: class (or name) of the model to be related in Sequence.
    :param child_key: key field on the child object to be used as the map key.
    :param default: any mapping type
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, OrderedDict())
    converter = converters.to_mapping_field(cls, child_key)
    validator = _init_fields.init_validator(required, types.TypedMapping)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, metadata=dict(key=key)) 
Example #15
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
              required=True, repr=True, cmp=True, key=None):
    """
    Create new date field on a model.

    :param formatter: date formatter string (default: "%Y-%m-%d")
    :param default: any date or string that can be converted to a date value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, date)
    converter = converters.to_date_field(formatter)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, cmp=cmp,
                  metadata=dict(formatter=formatter, key=key)) 
Example #16
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
                  required=True, repr=True, cmp=True, key=None):
    """
    Create new datetime field on a model.

    :param formatter: datetime formatter string (default: "ISO_FORMAT")
    :param default: any datetime or string that can be converted to a datetime
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, datetime)
    converter = converters.to_datetime_field(formatter)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, cmp=cmp,
                  metadata=dict(formatter=formatter, key=key)) 
Example #17
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
                 key=None):
    """
    Create new int field on a model.

    :param default: any integer value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, int)
    return attrib(default=default, converter=converters.int_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #18
Source File: fields.py    From related with MIT License 6 votes vote down vote up
def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
              required=True, repr=True, cmp=True, key=None):
    """
    Create new time field on a model.

    :param formatter: time formatter string (default: "%H:%M:%S")
    :param default: any time or string that can be converted to a time value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, time)
    converter = converters.to_time_field(formatter)
    return attrib(default=default, converter=converter, validator=validator,
                  repr=repr, cmp=cmp,
                  metadata=dict(formatter=formatter, key=key)) 
Example #19
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def optional_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields values
    for that attribute. The strategy generates optional integers.
    """
    default = NOTHING
    val_strat = st.integers() | st.none()
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(val_strat)

    return (attr.ib(default=default), val_strat) 
Example #20
Source File: __init__.py    From ueberzug with GNU General Public License v3.0 5 votes vote down vote up
def __getattr__(self, name):
        if name not in self.__ATTRIBUTES:
            raise AttributeError("There is no attribute named %s" % name)

        attribute = self.__ATTRIBUTES[name]

        if name in self.__data:
            return self.__data[name]
        if attribute.default != attr.NOTHING:
            return attribute.default
        return None 
Example #21
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def lists_of_attrs(defaults=None, min_size=0):
    # Python functions support up to 255 arguments.
    return st.lists(
        simple_attrs(defaults), min_size=min_size, max_size=10
    ).map(lambda l: sorted(l, key=lambda t: t[0]._default is not NOTHING)) 
Example #22
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def lists_of_typed_attrs(defaults=None):
    # Python functions support up to 255 arguments.
    return lists(simple_typed_attrs(defaults), max_size=50).map(
        lambda l: sorted(l, key=lambda t: t[0]._default is not NOTHING)
    ) 
Example #23
Source File: fields.py    From related with MIT License 5 votes vote down vote up
def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
                 key=None):
    """
    Create new bool field on a model.

    :param default: any boolean value
    :param bool required: whether or not the object is invalid if not provided.
    :param bool repr: include this field should appear in object's repr.
    :param bool cmp: include this field in generated comparison.
    :param string key: override name of the value when converted to dict.
    """
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, bool)
    return attrib(default=default, validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key)) 
Example #24
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def int_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields ints for that
    attribute.
    """
    default = attr.NOTHING
    if defaults is True or (defaults is None and draw(booleans())):
        default = draw(integers())
    return (attr.ib(type=int, default=default), integers()) 
Example #25
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def str_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields strs for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(booleans())):
        default = draw(text())
    return (attr.ib(type=unicode, default=default), text()) 
Example #26
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def float_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields floats for that
    attribute.
    """
    default = attr.NOTHING
    if defaults is True or (defaults is None and draw(booleans())):
        default = draw(floats())
    return (attr.ib(type=float, default=default), floats()) 
Example #27
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def dict_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields dictionaries
    for that attribute. The dictionaries map strings to integers.
    """
    default = attr.NOTHING
    val_strat = dictionaries(keys=text(), values=integers())
    if defaults is True or (defaults is None and draw(booleans())):
        default = draw(val_strat)
    return (attr.ib(type=Dict[unicode, int], default=default), val_strat) 
Example #28
Source File: xr_accessor.py    From xarray-simlab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reset_vars(self, model=None):
        """Set or reset Dataset variables with model input default
        values (if any).

        Parameters
        ----------
        model : :class:`xsimlab.Model` object, optional
            Reference model. If None, tries to get model from context.

        Returns
        -------
        updated : Dataset
            Another Dataset with new and/or replaced variables.

        See Also
        --------
        :meth:`Dataset.xsimlab.update_vars`

        """
        model = _maybe_get_model_from_context(model)

        ds = self._ds.copy()

        input_vars_default = {}

        for p_name, var_name in model.input_vars:
            p_obj = model[p_name]
            var = variables_dict(type(p_obj))[var_name]

            if var.default is not attr.NOTHING:
                input_vars_default[(p_name, var_name)] = var.default

        ds.xsimlab._set_input_vars(model, input_vars_default)

        return ds 
Example #29
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def float_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields floats for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(st.floats())
    return (attr.ib(default=default), st.floats()) 
Example #30
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def str_attrs(draw, defaults=None, type_annotations=None):
    """
    Generate a tuple of an attribute and a strategy that yields strs for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(st.text())
    if (type_annotations is None and draw(st.booleans())) or type_annotations:
        type = unicode
    else:
        type = None
    return (attr.ib(default=default, type=type), st.text())