本文整理汇总了Python中attr.fields方法的典型用法代码示例。如果您正苦于以下问题:Python attr.fields方法的具体用法?Python attr.fields怎么用?Python attr.fields使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类attr
的用法示例。
在下文中一共展示了attr.fields方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resolve_types
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def resolve_types(cls, global_ns=None, local_ns=None):
"""
Resolve any strings and forward annotations in type annotations.
:param type cls: Class to resolve.
:param globalns: Dictionary containing global variables, if needed.
:param localns: Dictionary containing local variables, if needed.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:raise NameError: If types cannot be resolved because of missing variables.
"""
hints = typing.get_type_hints(cls, globalns=global_ns, localns=local_ns)
for field in attr.fields(cls):
if field.name in hints:
# Since fields have been frozen we must work around it.
object.__setattr__(field, "type", hints[field.name])
示例2: _to_type_from_attrs
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def _to_type_from_attrs(spec) -> Type:
"""Converts an `attr.s` class or instance to a `tff.Type`."""
if isinstance(spec, type):
# attrs class type, introspect the attributes for their type annotations.
elements = [(a.name, a.type) for a in attr.fields(spec)]
missing_types = [n for (n, t) in elements if not t]
if missing_types:
raise TypeError((
"Cannot infer tff.Type for attr.s class '{}' because some attributes "
'were missing type specifications: {}').format(
spec.__name__, missing_types))
the_type = spec
else:
# attrs class instance, inspect the field values for instances convertible
# to types.
elements = attr.asdict(
spec, dict_factory=collections.OrderedDict, recurse=False)
the_type = type(spec)
return NamedTupleTypeWithPyContainerType(elements, the_type)
示例3: __init__
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def __init__(self, strategy, source="<string>"):
self._config = ConfigParser(default_section="strategy", interpolation=None)
self._config.read_string(strategy, source)
self._situations = dict()
for name in self._config.sections():
# configparser set non-specified values to '', we want default to None
attr_names = [a.name for a in attr.fields(_Situation)]
values = dict.fromkeys(attr_names, None)
for key, val in self._config[name].items():
# filter out fields not implemented, otherwise it would
# cause TypeError for _Situation constructor
if (not val) or (key not in attr_names):
continue
elif key in _POSITIONS:
values[key] = Range(val)
else:
values[key] = val
self._situations[name] = _Situation(**values)
self._tuple = tuple(self._situations.values())
示例4: test_metadata_present
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_metadata_present(self, list_of_attrs):
"""
Assert dictionaries are copied and present.
"""
C = make_class("C", dict(zip(gen_attr_names(), list_of_attrs)))
for hyp_attr, class_attr in zip(list_of_attrs, fields(C)):
if hyp_attr.metadata is None:
# The default is a singleton empty dict.
assert class_attr.metadata is not None
assert len(class_attr.metadata) == 0
else:
assert hyp_attr.metadata == class_attr.metadata
# Once more, just to assert getting items and iteration.
for k in class_attr.metadata:
assert hyp_attr.metadata[k] == class_attr.metadata[k]
assert hyp_attr.metadata.get(k) == class_attr.metadata.get(
k
)
示例5: test_metadata_immutability
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_metadata_immutability(self, C, string):
"""
The metadata dict should be best-effort immutable.
"""
for a in fields(C):
with pytest.raises(TypeError):
a.metadata[string] = string
with pytest.raises(AttributeError):
a.metadata.update({string: string})
with pytest.raises(AttributeError):
a.metadata.clear()
with pytest.raises(AttributeError):
a.metadata.setdefault(string, string)
for k in a.metadata:
# For some reason, Python 3's MappingProxyType throws an
# IndexError for deletes on a large integer key.
with pytest.raises((TypeError, IndexError)):
del a.metadata[k]
with pytest.raises(AttributeError):
a.metadata.pop(k)
with pytest.raises(AttributeError):
a.metadata.popitem()
示例6: test_basic_annotations
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_basic_annotations(self):
"""
Sets the `Attribute.type` attr from basic type annotations.
"""
@attr.s
class C:
x: int = attr.ib()
y = attr.ib(type=str)
z = attr.ib()
assert int is attr.fields(C).x.type
assert str is attr.fields(C).y.type
assert None is attr.fields(C).z.type
assert C.__init__.__annotations__ == {
"x": int,
"y": str,
"return": None,
}
示例7: test_typing_annotations
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_typing_annotations(self):
"""
Sets the `Attribute.type` attr from typing annotations.
"""
@attr.s
class C:
x: typing.List[int] = attr.ib()
y = attr.ib(type=typing.Optional[str])
assert typing.List[int] is attr.fields(C).x.type
assert typing.Optional[str] is attr.fields(C).y.type
assert C.__init__.__annotations__ == {
"x": typing.List[int],
"y": typing.Optional[str],
"return": None,
}
示例8: test_recurse_property
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [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)
示例9: test_change
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_change(self, C, data):
"""
Changes work.
"""
# Take the first attribute, and change it.
assume(fields(C)) # Skip classes with no attributes.
field_names = [a.name for a in fields(C)]
original = C()
chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
change_dict = {name: data.draw(st.integers()) for name in chosen_names}
with pytest.deprecated_call():
changed = assoc(original, **change_dict)
for k, v in change_dict.items():
assert getattr(changed, k) == v
示例10: from_pipfile
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def from_pipfile(cls, name, pipfile):
# type: (S, TPIPFILE) -> NamedRequirement
creation_args = {} # type: TPIPFILE
if hasattr(pipfile, "keys"):
attr_fields = [field.name for field in attr.fields(cls)]
creation_args = {
k: v for k, v in pipfile.items() if k in attr_fields
} # type: ignore
creation_args["name"] = name
version = get_version(pipfile) # type: Optional[STRING_TYPE]
extras = creation_args.get("extras", None)
creation_args["version"] = version # type: ignore
req = init_requirement("{0}{1}".format(name, version))
if req and extras and req.extras and isinstance(req.extras, tuple):
if isinstance(extras, six.string_types):
req.extras = (extras) + tuple(["{0}".format(xtra) for xtra in req.extras])
elif isinstance(extras, (tuple, list)):
req.extras += tuple(extras)
creation_args["req"] = req
return cls(**creation_args) # type: ignore
示例11: from_pipfile
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def from_pipfile(cls, name, pipfile):
attr_fields = [field.name for field in attr.fields(cls)]
found_keys = [k for k in pipfile.keys() if k in attr_fields]
marker_strings = ["{0} {1}".format(k, pipfile[k]) for k in found_keys]
if pipfile.get("markers"):
marker_strings.append(pipfile.get("markers"))
markers = set()
for marker in marker_strings:
markers.add(marker)
combined_marker = None
try:
combined_marker = cls.make_marker(" and ".join(sorted(markers)))
except RequirementError:
pass
else:
return combined_marker
示例12: _to_config
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def _to_config(config_cls, default_get, environ, prefix):
vals = {}
for a in attr.fields(config_cls):
try:
ce = a.metadata[CNF_KEY]
except KeyError:
continue
if ce.sub_cls is None:
get = ce.callback or default_get
val = get(environ, a.metadata, prefix, a.name)
else:
val = _to_config(
ce.sub_cls, default_get, environ,
prefix + ((a.name if prefix else a.name),)
)
vals[a.name] = val
return config_cls(**vals)
示例13: _to_config
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def _to_config(config_cls, default_get, environ, prefix):
vals = {}
for a in attr.fields(config_cls):
try:
ce = a.metadata[CNF_KEY]
except KeyError:
continue
if ce.sub_cls is None:
get = ce.callback or default_get
val = get(environ, a.metadata, prefix, a.name)
else:
val = _to_config(
ce.sub_cls,
default_get,
environ,
prefix + ((a.name if prefix else a.name),),
)
vals[a.name] = val
return config_cls(**vals)
示例14: test_structure_simple_from_dict_default
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
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)
示例15: test_structure_union
# 需要导入模块: import attr [as 别名]
# 或者: from attr import fields [as 别名]
def test_structure_union(converter, cl_and_vals_a, cl_and_vals_b):
"""Structuring of automatically-disambiguable unions works."""
cl_a, vals_a = cl_and_vals_a
cl_b, vals_b = cl_and_vals_b
a_field_names = {a.name for a in fields(cl_a)}
b_field_names = {a.name for a in fields(cl_b)}
assume(a_field_names)
assume(b_field_names)
common_names = a_field_names & b_field_names
if len(a_field_names) > len(common_names):
obj = cl_a(*vals_a)
dumped = asdict(obj)
res = converter.structure(dumped, Union[cl_a, cl_b])
assert isinstance(res, cl_a)
assert obj == res