本文整理匯總了Python中attr.asdict方法的典型用法代碼示例。如果您正苦於以下問題:Python attr.asdict方法的具體用法?Python attr.asdict怎麽用?Python attr.asdict使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類attr
的用法示例。
在下文中一共展示了attr.asdict方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_repository_preserve
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def test_repository_preserve(converter):
repo = RepositoriesRegistry()
repo.add_repo(url='https://example.com', name='insane')
repo.add_repo(url='https://pypi.org/simple/', name='pypi')
root = RootDependency()
dep1 = DependencyMaker.from_params(
source=root,
raw_name='dephell',
constraint='*',
repo=repo,
)[0]
req = Requirement(dep=dep1, roots=[root.name], lock=False)
content1 = converter.dumps([req], project=root)
root2 = converter.loads(content1)
assert len(root2.dependencies) == 1
dep2 = root2.dependencies[0]
repos1 = [attr.asdict(repo) for repo in dep1.repo.repos]
repos2 = [attr.asdict(repo) for repo in dep2.repo.repos]
assert repos1 == repos2
示例2: prepare_for_json
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def prepare_for_json(obj):
if isinstance(obj, (list, tuple, set)):
return [prepare_for_json(x) for x in obj]
elif issubclass(obj.__class__, enum.Enum):
return obj.value
elif isinstance(obj, dict):
return {
prepare_for_json(k): prepare_for_json(v)
for k, v in obj.items()
if v is not None
and ((isinstance(v, list) and v) or not isinstance(v, list))
}
elif isinstance(obj, str):
return obj
try:
return prepare_for_json(attr.asdict(obj))
except attr.exceptions.NotAnAttrsClassError:
pass
return obj
示例3: _to_type_from_attrs
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [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)
示例4: dump
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def dump(self, app_name):
"""Store information in a cache."""
cache = self._cache(app_name)
# Attempt to write out our version check file
with lockfile.LockFile(str(cache)):
if cache.exists():
with cache.open() as fp:
state = json.load(fp)
else:
state = {}
state[sys.prefix] = attr.asdict(self)
with cache.open('w') as fp:
json.dump(state, fp, sort_keys=True)
示例5: test_asdict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def test_asdict(self):
ts = msprime.simulate(10, mutation_rate=1, random_seed=1)
t = ts.tables
self.add_metadata(t)
d1 = {
"encoding_version": (1, 1),
"sequence_length": t.sequence_length,
"metadata_schema": str(t.metadata_schema),
"metadata": t.metadata_schema.encode_row(t.metadata),
"individuals": t.individuals.asdict(),
"populations": t.populations.asdict(),
"nodes": t.nodes.asdict(),
"edges": t.edges.asdict(),
"sites": t.sites.asdict(),
"mutations": t.mutations.asdict(),
"migrations": t.migrations.asdict(),
"provenances": t.provenances.asdict(),
}
d2 = t.asdict()
self.assertEqual(set(d1.keys()), set(d2.keys()))
t1 = tskit.TableCollection.fromdict(d1)
t2 = tskit.TableCollection.fromdict(d2)
self.assertEqual(t1, t2)
示例6: test_from_dict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def test_from_dict(self):
ts = msprime.simulate(10, mutation_rate=1, random_seed=1)
t1 = ts.tables
self.add_metadata(t1)
d = {
"encoding_version": (1, 1),
"sequence_length": t1.sequence_length,
"metadata_schema": str(t1.metadata_schema),
"metadata": t1.metadata_schema.encode_row(t1.metadata),
"individuals": t1.individuals.asdict(),
"populations": t1.populations.asdict(),
"nodes": t1.nodes.asdict(),
"edges": t1.edges.asdict(),
"sites": t1.sites.asdict(),
"mutations": t1.mutations.asdict(),
"migrations": t1.migrations.asdict(),
"provenances": t1.provenances.asdict(),
}
t2 = tskit.TableCollection.fromdict(d)
self.assertEquals(t1, t2)
示例7: get_execution_info
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def get_execution_info(self, current_task):
# type: (...) -> ExecutionInfo
try:
execution = ExecutionInfo.from_task(current_task)
except Exception as e:
self.error("Could not parse task execution info: {}".format(e.args[0]))
current_task.failed(
status_reason=e.args[0], status_message=self._task_status_change_message
)
self.exit(e.args[0])
if "\\" in execution.working_dir:
warning(
'Working dir "{}" contains backslashes. '
"All path separators must be forward slashes.".format(
execution.working_dir
)
)
print("Executing task id [%s]:" % current_task.id)
for pair in attr.asdict(execution).items():
print("{} = {}".format(*pair))
print()
return execution
示例8: json_ready_header_auth
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def json_ready_header_auth(header_auth):
# type: (MessageHeaderAuthentication) -> Dict[str, Text]
"""Create a JSON-serializable representation of a
:class:`aws_encryption_sdk.internal.structures.MessageHeaderAuthentication`.
http://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-authentication
:param header_auth: header auth for which to create a JSON-serializable representation
:type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:rtype: dict
"""
dict_header_auth = attr.asdict(header_auth)
for key, value in dict_header_auth.items():
dict_header_auth[key] = unicode_b64_encode(value)
return dict_header_auth
示例9: dump_devinfo
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def dump_devinfo(dev: Device, file):
"""Dump developer information.
Pass `file` to write the results directly into a file.
"""
import attr
methods = await dev.get_supported_methods()
res = {
"supported_methods": {k: v.asdict() for k, v in methods.items()},
"settings": [attr.asdict(x) for x in await dev.get_settings()],
"sysinfo": attr.asdict(await dev.get_system_info()),
"interface_info": attr.asdict(await dev.get_interface_information()),
}
if file:
click.echo("Saving to file: %s" % file.name)
json.dump(res, file, sort_keys=True, indent=4)
else:
click.echo(json.dumps(res, sort_keys=True, indent=4))
示例10: create_specification
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def create_specification(self):
"""
Create a new chute specification from the existing chute.
This is a completely clean copy of all information necessary to rebuild
the Chute object. It should contain only primitive types, which can
easily be serialized as JSON or YAML.
"""
def no_privates(a, _):
return not a.name.startswith('_')
return attr.asdict(self, filter=no_privates)
示例11: _as_dict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def _as_dict(self):
return attr.asdict(self, recurse=False)
示例12: to_step_dict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def to_step_dict(self):
step_dict = {k: v for k, v in self._as_dict().iteritems()
if k == 'name' or v != PROTOTYPE_STEP[k]}
if step_dict.get('cmd', None) is not None:
step_dict['cmd'] = list(step_dict['cmd'])
if step_dict.get('cost', None) is not None:
cost = step_dict['cost']
step_dict['cost'] = attr.asdict(cost)
for k in step_dict.keys():
if k.startswith('_'):
step_dict[k[1:]] = step_dict.pop(k)
return step_dict
示例13: asdict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def asdict(self):
"""Returns this SimpleRecipesCfg as a JSON-serializable dict.
This is mostly the same as `attr.asdict`, except that it knows how to
deal with the fact that SimpleRecipesCfg.deps is a FrozenDict."""
ret = attr.asdict(self)
ret['deps'] = {k: attr.asdict(v) for k, v in ret['deps'].iteritems()}
ret['project_id'] = ret['repo_name'] # Alias repo_name<->project_id
return ret
示例14: _asdict
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def _asdict(self):
ret = thaw(attr.asdict(self, filter=(lambda attr, val: (
(val and val != attr.default or (attr.name in self._RENDER_WHITELIST)) and
attr.name not in self._RENDER_BLACKLIST
))))
if self.env_prefixes.mapping:
ret['env_prefixes'] = dict(self.env_prefixes.mapping)
if self.env_suffixes.mapping:
ret['env_suffixes'] = dict(self.env_suffixes.mapping)
return ret
示例15: __iter__
# 需要導入模塊: import attr [as 別名]
# 或者: from attr import asdict [as 別名]
def __iter__(self):
return iter(k for k, v in attr.asdict(self).items() if v is not None)