本文整理汇总了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))
示例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)
示例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)
示例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
示例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}'"
)
示例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)
示例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
示例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
示例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))
示例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
示例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)
示例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)
示例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)
示例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])
示例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