当前位置: 首页>>代码示例>>Python>>正文


Python attr.attrs方法代码示例

本文整理汇总了Python中attr.attrs方法的典型用法代码示例。如果您正苦于以下问题:Python attr.attrs方法的具体用法?Python attr.attrs怎么用?Python attr.attrs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在attr的用法示例。


在下文中一共展示了attr.attrs方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_enforces_type

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_enforces_type(self):
        """
        The `hash` argument to both attrs and attrib must be None, True, or
        False.
        """
        exc_args = ("Invalid value for hash.  Must be True, False, or None.",)

        with pytest.raises(TypeError) as e:
            make_class("C", {}, hash=1),

        assert exc_args == e.value.args

        with pytest.raises(TypeError) as e:
            make_class("C", {"a": attr.ib(hash=1)}),

        assert exc_args == e.value.args 
开发者ID:python-attrs,项目名称:attrs,代码行数:18,代码来源:test_dunders.py

示例2: test_enforce_no_cache_hash_without_hash

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_enforce_no_cache_hash_without_hash(self):
        """
        Ensure exception is thrown if caching the hash code is requested
        but attrs is not requested to generate `__hash__`.
        """
        exc_args = (
            "Invalid value for cache_hash.  To use hash caching,"
            " hashing must be either explicitly or implicitly "
            "enabled.",
        )
        with pytest.raises(TypeError) as e:
            make_class("C", {}, hash=False, cache_hash=True)
        assert exc_args == e.value.args

        # unhashable case
        with pytest.raises(TypeError) as e:
            make_class(
                "C", {}, hash=None, eq=True, frozen=False, cache_hash=True
            )
        assert exc_args == e.value.args 
开发者ID:python-attrs,项目名称:attrs,代码行数:22,代码来源:test_dunders.py

示例3: test_cache_hash_serialization_hash_cleared

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_cache_hash_serialization_hash_cleared(self, klass, cached):
        """
        Tests that the hash cache is cleared on deserialization to fix
        https://github.com/python-attrs/attrs/issues/482 .

        This test is intended to guard against a stale hash code surviving
        across serialization (which may cause problems when the hash value
        is different in different interpreters).
        """

        obj = klass(IncrementingHasher())
        original_hash = hash(obj)
        obj_rt = self._roundtrip_pickle(obj)

        if cached:
            assert original_hash == hash(obj)

        assert original_hash != hash(obj_rt) 
开发者ID:python-attrs,项目名称:attrs,代码行数:20,代码来源:test_dunders.py

示例4: test_validator_others

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_validator_others(self, slots):
        """
        Does not interfere when setting non-attrs attributes.
        """
        C = make_class(
            "C", {"a": attr.ib("a", validator=instance_of(int))}, slots=slots
        )
        i = C(1)

        assert 1 == i.a

        if not slots:
            i.b = "foo"
            assert "foo" == i.b
        else:
            with pytest.raises(AttributeError):
                i.b = "foo" 
开发者ID:python-attrs,项目名称:attrs,代码行数:19,代码来源:test_dunders.py

示例5: mutable

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def mutable(maybe_cls=None, strict=False):

    def wrap(cls):
        wrapped = attrs(cls)
        wrapped.__related_strict__ = strict
        return wrapped

    return wrap(maybe_cls) if maybe_cls is not None else wrap 
开发者ID:genomoncology,项目名称:related,代码行数:10,代码来源:decorators.py

示例6: immutable

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def immutable(maybe_cls=None, strict=False):

    def wrap(cls):
        wrapped = attrs(cls, frozen=True, slots=True)
        wrapped.__related_strict__ = strict
        return wrapped

    return wrap(maybe_cls) if maybe_cls is not None else wrap 
开发者ID:genomoncology,项目名称:related,代码行数:10,代码来源:decorators.py

示例7: to_settings

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def to_settings(self) -> Dict:
        settings = {}
        attrs = attr.fields(self.__class__)
        for attribute in attrs:
            if attribute.name == "path":
                continue
            value = getattr(self, attribute.name)
            if value is None:
                continue
            settings[attribute.name.replace("_", "-")] = value
        return settings 
开发者ID:hh-h,项目名称:aiohttp-swagger3,代码行数:13,代码来源:ui_settings.py

示例8: __init__

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def __init__(self, *args, **kwargs):
        if any(x in kwargs for x in ("eq", "order")):
            raise RuntimeError("Only `cmp` is supported for attr.attrs, not `eq` or `order`")
        if Version(attr.__version__) >= Version("19.2"):
            cmp = kwargs.pop("cmp", None)
            if cmp is not None:
                kwargs["eq"] = kwargs["order"] = cmp
        self.args = args
        self.kwargs = kwargs 
开发者ID:allegroai,项目名称:trains,代码行数:11,代码来源:attrs.py

示例9: __call__

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def __call__(self, f):
        return attr.attrs(*self.args, **self.kwargs)(f) 
开发者ID:allegroai,项目名称:trains,代码行数:4,代码来源:attrs.py

示例10: test_enforce_no_cached_hash_without_init

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_enforce_no_cached_hash_without_init(self):
        """
        Ensure exception is thrown if caching the hash code is requested
        but attrs is not requested to generate `__init__`.
        """
        exc_args = (
            "Invalid value for cache_hash.  To use hash caching,"
            " init must be True.",
        )
        with pytest.raises(TypeError) as e:
            make_class("C", {}, init=False, hash=True, cache_hash=True)
        assert exc_args == e.value.args 
开发者ID:python-attrs,项目名称:attrs,代码行数:14,代码来源:test_dunders.py

示例11: assert_apicall_equals

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def assert_apicall_equals(self, expected, actual_api_call):
        # models.APICall has its own __eq__ method from attrs,
        # but in practice the assertion errors are unreadable and
        # it's not always clear which part of the API call object is
        # wrong.  To get better error messages each field is individually
        # compared.
        assert isinstance(expected, models.APICall)
        assert isinstance(actual_api_call, models.APICall)
        assert expected.method_name == actual_api_call.method_name
        assert expected.params == actual_api_call.params 
开发者ID:aws,项目名称:chalice,代码行数:12,代码来源:test_planner.py

示例12: test_unknown_model_type_raises_error

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def test_unknown_model_type_raises_error(self):

        @attr.attrs
        class Foo(models.ManagedModel):
            resource_type = 'foo'

        foo = Foo(resource_name='myfoo')
        with pytest.raises(ValueError):
            self.remote_state.resource_exists(foo) 
开发者ID:aws,项目名称:chalice,代码行数:11,代码来源:test_planner.py

示例13: simple_attr

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def simple_attr():
    """
    Return an attribute with a name just for testing purpose.
    """

    @attr.attrs
    class C:
        test = attr.attrib()

    return attr.fields_dict(C)["test"] 
开发者ID:benbovy,项目名称:xarray-simlab,代码行数:12,代码来源:test_validators.py

示例14: process

# 需要导入模块: import attr [as 别名]
# 或者: from attr import attrs [as 别名]
def process(maybe_cls=None, autodoc=True):
    """A class decorator that adds everything needed to use the class
    as a process.

    A process represents a logical unit in a computational model.

    A process class usually implements:

    - An interface as a set of variables defined as class attributes (see
      :func:`variable`, :func:`on_demand`, :func:`foreign` and :func:`group`).
      When the class is used within a :class:`Model` object, this decorator
      automatically adds properties to get/set values for these variables.

    - One or more methods among ``initialize()``, ``run_step()``,
      ``finalize_step()`` and ``finalize()``, which are called at different
      stages of a simulation and perform some computation based on the
      variables defined in the process interface.

    - Decorated methods to compute, validate or set a default value for one or
      more variables.

    Parameters
    ----------
    maybe_cls : class, optional
        Allows to apply this decorator to a class either as ``@process`` or
        ``@process(*args)``.
    autodoc : bool, optional
        (default: True) Automatically adds an attributes section to the
        docstring of the class to which the decorator is applied, using the
        metadata of each variable declared in the class.

    """

    def wrap(cls):
        attr_cls = attr.attrs(cls, repr=False)

        builder = _ProcessBuilder(attr_cls)

        builder.add_properties()

        if autodoc:
            builder.render_docstrings()

        setattr(attr_cls, "__xsimlab_cls__", builder.build_class())

        return attr_cls

    if maybe_cls is None:
        return wrap
    else:
        return wrap(maybe_cls) 
开发者ID:benbovy,项目名称:xarray-simlab,代码行数:53,代码来源:process.py


注:本文中的attr.attrs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。