Python attr 模块,NOTHING 实例源码

我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用attr.NOTHING

项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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))
项目:jsonschema-extractor    作者:toumorokoshi    | 项目源码 | 文件源码
def _extract_attribute(cls, extractor, attribute):
        is_required = attribute.default is attr.NOTHING

        schema = None
        if "jsonschema" in attribute.metadata:
            schema = attribute.metadata["jsonschema"]
        elif attribute.type is not None:
            schema = extractor.extract(attribute.type)
        else:
            for validator in _iterate_validator(attribute.validator):
                if isinstance(validator, _InstanceOfValidator):
                    schema = extractor.extract(validator.type)

        if schema is None:
            raise UnextractableSchema(
                "all attributes must have an 'InstanceOfValidator'. attribute {0} does not.".format(attribute)
            )
        return AttributeDetails(
            attribute.name, schema, is_required
        )
项目:python-gogs-client    作者:unfoldingWord-dev    | 项目源码 | 文件源码
def from_json(cls, parsed_json):
        # with introspection, get arguments of the constructor
        parsed_json['json'] = parsed_json.copy()
        params = cls.__attrs_attrs__
        args = []
        kwargs = OrderedDict()
        for param in params:
            param_name = param.name.lstrip('_')
            # if not a keyword argument
            if param.default == attr.NOTHING:
                args.append(json_get(parsed_json, param_name))
            # if it's a keyword argument
            else:
                kwargs[param_name] = parsed_json.get(param_name, None)
        o = cls(*args, **kwargs)
        return o
项目:python-gogs-client    作者:unfoldingWord-dev    | 项目源码 | 文件源码
def from_json(cls, parsed_json):
        # with introspection, get arguments of the constructor
        parsed_json['json'] = parsed_json.copy()
        params = cls.__attrs_attrs__
        args = []
        kwargs = OrderedDict()
        for param in params:
            param_name = param.name.lstrip('_')
            # if not a keyword argument
            if param.default == attr.NOTHING:
                args.append(json_get(parsed_json, param_name))
            # if it's a keyword argument
            else:
                kwargs[param_name] = parsed_json.get(param_name, None)
        o = cls(*args, **kwargs)
        return o
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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, cls)
    return attrib(default=default, convert=converter, validator=validator,
                  repr=repr, cmp=cmp, metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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 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, convert=converter, validator=validator,
                  repr=repr, cmp=cmp,
                  metadata=dict(formatter=formatter, key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
               key=None):
    """
    Create new float field on a model.

    :param default: any float 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, float)
    return attrib(default=default, convert=converters.float_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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, convert=converters.int_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
               key=None):
    """
    Create new str field on a model.

    :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, convert=converters.str_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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, convert=converter, validator=validator,
                  repr=repr, metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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, convert=converter, validator=validator,
                  repr=repr, metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
def StringField(default=NOTHING, required=True, repr=True, cmp=True,
                key=None):
    """
    Create new str field on a model.

    :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)
    return attrib(default=default, convert=converters.str_if_not_none,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
def URLField(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 = ParseResult
    default = _init_fields.init_default(required, default, None)
    validator = _init_fields.init_validator(required, cls)
    return attrib(default=default, convert=converters.str_to_url,
                  validator=validator, repr=repr, cmp=cmp,
                  metadata=dict(key=key))
项目:aiobearychat    作者:mozillazg    | 项目源码 | 文件源码
def test_clean_nothing_keys():
    d = {
        'a': 'b',
        'c': attr.NOTHING,
    }
    result = sansio.clean_nothing_keys(d)
    assert 'c' not in result
项目:aiobearychat    作者:mozillazg    | 项目源码 | 文件源码
def __init__(self, session: aiohttp.ClientSession,
                 token: str = attr.NOTHING, *,
                 base_url: str = ''):
        requester = Requester(session=session)  # type: Requester
        super().__init__(requester=requester, token=token, base_url=base_url)
项目:aiobearychat    作者:mozillazg    | 项目源码 | 文件源码
def __init__(self, session: aiohttp.ClientSession,
                 token: str = attr.NOTHING, *,
                 base_url: str = ''):
        requester = Requester(session=session)  # type: Requester
        super().__init__(requester=requester, token=token, base_url=base_url)
项目:aiobearychat    作者:mozillazg    | 项目源码 | 文件源码
def __init__(self, requester: Requester, token: str = NOTHING, *,
                 base_url: str = ''):
        #: RTM HTTP API ????
        self.base_url = base_url or self.base_url  # type: str
        self._token = token    # type: str
        super().__init__(requester=requester, token=self._token,
                         base_url=self.base_url)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def lists_of_typed_attrs(defaults=None):
    # Python functions support up to 255 arguments.
    return (lists(simple_typed_attrs(defaults), average_size=9, max_size=50)
            .map(lambda l: sorted(l,
                                  key=lambda t: t[0]._default is not NOTHING)))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def bare_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields values
    appropriate for that attribute.
    """
    default = attr.NOTHING
    if defaults is True or (defaults is None and draw(booleans())):
        default = None
    return ((attr.ib(type=Any, default=default), just(None)))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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()))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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()))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def bare_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields values
    appropriate for that attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = None
    return ((attr.ib(default=default), st.just(None)))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def int_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields ints for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(st.integers())
    return ((attr.ib(default=default), st.integers()))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
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()))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def dict_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 = NOTHING
    val_strat = st.dictionaries(keys=st.text(), values=st.integers())
    if defaults is True or (defaults is None and draw(st.booleans())):
        default_val = draw(val_strat)
        default = attr.Factory(lambda: default_val)
    return ((attr.ib(default=default), val_strat))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def lists_of_attrs(defaults=None):
    # Python functions support up to 255 arguments.
    return (st.lists(simple_attrs(defaults), average_size=5, max_size=20)
            .map(lambda l: sorted(l,
                                  key=lambda t: t[0]._default is not NOTHING)))
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def structure_attrs_fromdict(self, obj, cl):
        # type: (Mapping, Type) -> Any
        """Instantiate an attrs class from a mapping (dict)."""
        # For public use.
        conv_obj = obj.copy()  # Dict of converted parameters.
        for a in cl.__attrs_attrs__:
            name = a.name
            # We detect the type by metadata.
            converted = self._structure_attr_from_dict(a, name, obj)
            if converted is not NOTHING:
                conv_obj[name] = converted

        return cl(**conv_obj)
项目:cattrs    作者:Tinche    | 项目源码 | 文件源码
def _structure_attr_from_dict(self, a, name, mapping):
        """Handle an individual attrs attribute structuring."""
        val = mapping.get(name, NOTHING)
        if val is NOTHING:
            return NOTHING

        type_ = a.type
        if type_ is None:
            # No type.
            return val
        if _is_union_type(type_):
            if NoneType in type_.__args__ and val is None:
                return None
            return self._structure_union(val, type_)
        return self._structure.dispatch(type_)(val, type_)
项目:reobject    作者:onyb    | 项目源码 | 文件源码
def Field(*args, default=attr.NOTHING, **kwargs):
    if callable(default):
        default = attr.Factory(default)

    return attr.ib(*args, default=default, **kwargs)
项目:trip-based-public-transit-routing-algo    作者:mk-fg    | 项目源码 | 文件源码
def attr_init(factory_or_default=attr.NOTHING, **attr_kws):
    if callable(factory_or_default): factory_or_default = attr.Factory(factory_or_default)
    return attr.ib(default=factory_or_default, **attr_kws)
项目:related    作者:genomoncology    | 项目源码 | 文件源码
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))
项目:related    作者:genomoncology    | 项目源码 | 文件源码
def init_default(required, default, optional_default):
    """
    Returns optional default if field is not required and
    default was not provided.

    :param bool required: whether the field is required in a given model.
    :param default: default provided by creator of field.
    :param optional_default: default for the data type if none provided.
    :return: default or optional default based on inputs
    """
    if not required and default == NOTHING:
        default = optional_default

    return default
项目:aiobearychat    作者:mozillazg    | 项目源码 | 文件源码
def __init__(self, requester: Requester, token: str = attr.NOTHING, *,
                 base_url: str = ''):
        #: ?? API ????
        self.base_url = base_url or self.base_url  # type: str
        self._token = token    # type: str
        #: meta ?? API
        self.meta = MetaAPI(
            requester, token=token, base_url=self.base_url
        )  # type: MetaAPI
        #: ???? API
        self.team = TeamAPI(
            requester, token=token, base_url=self.base_url
        )  # type: TeamAPI
        #: ???? API
        self.user = UserAPI(
            requester, token=token, base_url=self.base_url
        )  # type: UserAPI
        #: ?????? API
        self.vchannel = VchannelAPI(
            requester, token=token, base_url=self.base_url
        )  # type: VchannelAPI
        #: ????? API
        self.channel = ChannelAPI(
            requester, token=token, base_url=self.base_url
        )  # type: ChannelAPI
        #: ??????? API
        self.session_channel = SessionChannelAPI(
            requester, token=token, base_url=self.base_url
        )  # type: SessionChannelAPI
        #: P2P ???? API
        self.p2p = P2pAPI(
            requester, token=token, base_url=self.base_url
        )  # type: P2pAPI
        #: ???? API
        self.message = MessageAPI(
            requester, token=token, base_url=self.base_url
        )  # type: MessageAPI
        #: ????? emoji ?? API
        self.emoji = EmojiAPI(
            requester, token=token, base_url=self.base_url
        )  # type: EmojiAPI
        #: ?? sticker ?? API
        self.sticker = StickerAPI(
            requester, token=token, base_url=self.base_url
        )  # type: StickerAPI
        #: RTM ?? API
        self.rtm = RtmAPI(
            requester, token=token, base_url=self.base_url
        )  # type: RtmAPI
项目:amqproto    作者:malinoff    | 项目源码 | 文件源码
def make_struct(cls, exclude_attrs=(), struct=c.Struct):
    """Helper function to make C-like structs from attrs-powered classes.
    Attributes become fields, annotations define C types.
    """
    # The whole thing is highly dependent on the internals of attrs :(
    # pylint: disable=protected-access
    struct_fields = []
    # Bits are accumulated into octets.
    bits = []
    type_ = None
    for name, attrib in _attribs_from(cls):
        if name in exclude_attrs:
            continue

        attrib = getattr(cls, name)
        type_ = cls.__annotations__[name]

        if type_ is d.Bit:
            bits.append(name / c.Flag)
            continue
        # In AMQP 0.9.1, all methods (that have bit fields) have sequential
        # bit fields that should (and technically can) be accumulated
        # into a single octet.
        if type_ is not d.Bit and bits:
            if len(bits) < 8:
                bits += [c.Padding(8 - len(bits))]
            bit_struct = c.Embedded(c.BitStruct(*reversed(bits)))
            struct_fields.append(bit_struct)
            bits = []
        if attrib._default is None:
            type_ = c.Default(type_, c.Pass)
        elif attrib._default is not attr.NOTHING and not attrib.init:
            type_ = c.Const(type_, attrib._default)

        struct_fields.append(name / type_)

    # Handle the case when a method ends with a bit field.
    if type_ is d.Bit:
        if len(bits) < 8:
            bits += [c.Padding(8 - len(bits))]
        bit_struct = c.Embedded(c.BitStruct(*reversed(bits)))
        struct_fields.append(bit_struct)

    return cls.__name__ / struct(*struct_fields)