python类NOTHING的实例源码

test_structure_attrs.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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))
attrs_extractor.py 文件源码 项目:jsonschema-extractor 作者: toumorokoshi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
        )
entities.py 文件源码 项目:python-gogs-client 作者: unfoldingWord-dev 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
entities.py 文件源码 项目:python-gogs-client 作者: unfoldingWord-dev 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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))
fields.py 文件源码 项目:related 作者: genomoncology 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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))
test_sansio.py 文件源码 项目:aiobearychat 作者: mozillazg 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_clean_nothing_keys():
    d = {
        'a': 'b',
        'c': attr.NOTHING,
    }
    result = sansio.clean_nothing_keys(d)
    assert 'c' not in result
aiohttp.py 文件源码 项目:aiobearychat 作者: mozillazg 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
aiohttp.py 文件源码 项目:aiobearychat 作者: mozillazg 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
http.py 文件源码 项目:aiobearychat 作者: mozillazg 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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)))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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()))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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()))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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()))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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()))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
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)))
converters.py 文件源码 项目:cattrs 作者: Tinche 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号