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


Python attr.has方法代码示例

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


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

示例1: is_named_tuple

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def is_named_tuple(value):
  """Determines whether `value` can be considered a `collections.namedtuple`.

  As `collections.namedtuple` creates a new class with no common a base for each
  named tuple, there is no simple way to check the type with `isintance(T)`.
  Instead, this method looks to see if `value` has an `_fields` attribute (which
  all namedtuple subclasses support).

  Args:
    value: an instance of a Python class or a Python type object.

  Returns:
    True iff `value` can be considered an instance or type of
    `collections.namedtuple`.
  """
  if isinstance(value, type):
    return issubclass(value, tuple) and hasattr(value, '_fields')
  else:
    return is_named_tuple(type(value)) 
开发者ID:tensorflow,项目名称:federated,代码行数:21,代码来源:py_typecheck.py

示例2: test_recurse_property

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def test_recurse_property(self, cls, tuple_class):
        """
        Property tests for recursive astuple.
        """
        obj = cls()
        obj_tuple = astuple(obj, tuple_factory=tuple_class)

        def assert_proper_tuple_class(obj, obj_tuple):
            assert isinstance(obj_tuple, tuple_class)
            for index, field in enumerate(fields(obj.__class__)):
                field_val = getattr(obj, field.name)
                if has(field_val.__class__):
                    # This field holds a class, recurse the assertions.
                    assert_proper_tuple_class(field_val, obj_tuple[index])

        assert_proper_tuple_class(obj, obj_tuple) 
开发者ID:python-attrs,项目名称:attrs,代码行数:18,代码来源:test_funcs.py

示例3: test_repr

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def test_repr(self, validator):
        """
        Returned validator has a useful `__repr__`.
        """
        v = optional(validator)

        if isinstance(validator, list):
            repr_s = (
                "<optional validator for _AndValidator(_validators=[{func}, "
                "<instance_of validator for type <{type} 'int'>>]) or None>"
            ).format(func=repr(always_pass), type=TYPE)
        else:
            repr_s = (
                "<optional validator for <instance_of validator for type "
                "<{type} 'int'>> or None>"
            ).format(type=TYPE)

        assert repr_s == repr(v) 
开发者ID:python-attrs,项目名称:attrs,代码行数:20,代码来源:test_validators.py

示例4: have_attr

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def have_attr(*args):
    if len(args) == 0:
        return False

    for a in args:
        if not attr.has(a.__class__):
            return False

    return True 
开发者ID:GoLP-IST,项目名称:nata,代码行数:11,代码来源:attrs.py

示例5: is_identifier

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def is_identifier(instance, attribute, value):
    if not value.isidentifier():
        raise ValueError(
            f"attribute {attribute.name} has an invalid string '{value}'"
        ) 
开发者ID:GoLP-IST,项目名称:nata,代码行数:7,代码来源:attrs.py

示例6: _to_dataset

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def _to_dataset(obj: Any, source: str) -> Optional[Metadata]:
    """
    Create Metadata from attr annotated object
    """
    if not attr.has(obj):
        return None

    type_name = obj.__module__ + '.' + obj.__class__.__name__
    data = unstructure(obj)

    return Metadata(type_name, source, data) 
开发者ID:apache,项目名称:airflow,代码行数:13,代码来源:__init__.py

示例7: __gt__

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def __gt__(self, other):
        """
        Called for [Operator] > [Outlet], so that if other is an attr annotated object
        it is set as an outlet of this Operator.
        """
        if not isinstance(other, Iterable):
            other = [other]

        for obj in other:
            if not attr.has(obj):
                raise TypeError(f"Left hand side ({obj}) is not an outlet")
        self.add_outlets(other)

        return self 
开发者ID:apache,项目名称:airflow,代码行数:16,代码来源:baseoperator.py

示例8: __lt__

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def __lt__(self, other):
        """
        Called for [Inlet] > [Operator] or [Operator] < [Inlet], so that if other is
        an attr annotated object it is set as an inlet to this operator
        """
        if not isinstance(other, Iterable):
            other = [other]

        for obj in other:
            if not attr.has(obj):
                raise TypeError(f"{obj} cannot be an inlet")
        self.add_inlets(other)

        return self 
开发者ID:apache,项目名称:airflow,代码行数:16,代码来源:baseoperator.py

示例9: dag

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def dag(self) -> Any:
        """
        Returns the Operator's DAG if set, otherwise raises an error
        """
        if self.has_dag():
            return self._dag
        else:
            raise AirflowException(
                'Operator {} has not been assigned to a DAG yet'.format(self)) 
开发者ID:apache,项目名称:airflow,代码行数:11,代码来源:baseoperator.py

示例10: dag_id

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def dag_id(self) -> str:
        """Returns dag id if it has one or an adhoc + owner"""
        if self.has_dag():
            return self.dag.dag_id
        else:
            return 'adhoc_' + self.owner 
开发者ID:apache,项目名称:airflow,代码行数:8,代码来源:baseoperator.py

示例11: _render_nested_template_fields

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def _render_nested_template_fields(
        self, content: Any, context: Dict, jinja_env: jinja2.Environment, seen_oids: Set
    ) -> None:
        if id(content) not in seen_oids:
            seen_oids.add(id(content))
            try:
                nested_template_fields = content.template_fields
            except AttributeError:
                # content has no inner template fields
                return

            self._do_render_template_fields(content, nested_template_fields, context, jinja_env, seen_oids) 
开发者ID:apache,项目名称:airflow,代码行数:14,代码来源:baseoperator.py

示例12: is_attrs

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def is_attrs(value):
  """Determines whether `value` is an attrs decorated class or instance of."""
  return attr.has(value) 
开发者ID:tensorflow,项目名称:federated,代码行数:5,代码来源:py_typecheck.py

示例13: structure

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def structure(d: Mapping, t: type) -> Any:
        """
        Helper method to structure a TrainerSettings class. Meant to be registered with
        cattr.register_structure_hook() and called with cattr.structure().
        """
        if not isinstance(d, Mapping):
            raise TrainerConfigError(f"Unsupported config {d} for {t.__name__}.")
        d_copy: Dict[str, Any] = {}
        d_copy.update(d)

        for key, val in d_copy.items():
            if attr.has(type(val)):
                # Don't convert already-converted attrs classes.
                continue
            if key == "hyperparameters":
                if "trainer_type" not in d_copy:
                    raise TrainerConfigError(
                        "Hyperparameters were specified but no trainer_type was given."
                    )
                else:
                    d_copy[key] = strict_to_cls(
                        d_copy[key], TrainerType(d_copy["trainer_type"]).to_settings()
                    )
            elif key == "max_steps":
                d_copy[key] = int(float(val))
                # In some legacy configs, max steps was specified as a float
            else:
                d_copy[key] = check_and_structure(key, val, t)
        return t(**d_copy) 
开发者ID:StepNeverStop,项目名称:RLs,代码行数:31,代码来源:settings.py

示例14: check_if_different

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def check_if_different(testobj1: object, testobj2: object) -> None:
    assert testobj1 is not testobj2
    if attr.has(testobj1.__class__) and attr.has(testobj2.__class__):
        for key, val in attr.asdict(testobj1, recurse=False).items():
            if isinstance(val, dict) or isinstance(val, list) or attr.has(val):
                # Note: this check doesn't check the contents of mutables.
                check_if_different(val, attr.asdict(testobj2, recurse=False)[key]) 
开发者ID:StepNeverStop,项目名称:RLs,代码行数:9,代码来源:test_settings.py

示例15: _serialize

# 需要导入模块: import attr [as 别名]
# 或者: from attr import has [as 别名]
def _serialize(val: Any) -> JSON:
    if isinstance(val, Serializable):
        return val.serialize()
    elif isinstance(val, (tuple, list, set)):
        return [_serialize(subval) for subval in val]
    elif isinstance(val, dict):
        return {_serialize(subkey): _serialize(subval) for subkey, subval in val.items()}
    elif attr.has(val.__class__):
        return _attrs_to_dict(val)
    return val 
开发者ID:tulir,项目名称:mautrix-python,代码行数:12,代码来源:serializable_attrs.py


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