Add support for "serialization" of deps to native Python objects
pombredanne opened this issue · 1 comments
Several objects and the objects in deps.py
in particular are plain (small) objects and they do not have the equivalent of a namedtuple._asdict()
or an attrs .asdict()
method or similar to return plain collections
and/or built-in types for easier integration such as for instance serializing to JSON. This would be a great addition. In contrast most of the deb822 objects have a mapping-like behavior (though that does not make them JSON-serializable either by default). And since they are collections.Mapping
they are easier to convert at once to actual built-in types.
For the sake of illustration here is a very simple external function that converts deps
objects to Python collections objects. It would much simpler to have this transform built-in the deps objects IMHO.
def deps_as_mapping(rel):
"""
Return a native Python collection from a `rel` deb_pkg_tools.deps.Relationship
object where every object is converted recursively to basic collections types e.g.
an OrderedDict or a list. Other types are left untouched.
"""
if isinstance(rel, (deps.RelationshipSet, deps.AlternativeRelationship,)):
return map(deps_as_mapping, rel.relationships)
if isinstance(rel, deps.VersionedRelationship):
return OrderedDict([
('name', rel.name),
('version', rel.version),
('operator', rel.operator),
])
# comes last as this is the least specialized type and the root of the
# inheritance hierarchy and they have no version and operator
# attribute therefore we return None for these for consistency.
if isinstance(rel, deps.Relationship):
return OrderedDict([
('name', rel.name),
('version', None),
('operator', None),
])
return rel