obsplus.utils.yield_obj_parent_attr¶
- obsplus.utils.yield_obj_parent_attr(obj, cls=None, is_attr=None, has_attr=None, basic_types=False)[source]¶
Recurse an object, yield a tuple of object, parent, attr.
Useful when data need to be changed or the provided DataFrame extractors don’t quite perform the desired task. Can also be used to extract relationships between entities in object trees to build a connecting graph.
- Parameters:
obj – The object to recurse through attributes of lists, tuples, and other instances.
cls – Only return instances of cls if not None, dont filter on types.
is_attr – Only return objects stored as attr_name, if None return all.
has_attr – Only return objects that have attribute has_attr, if None return all.
basic_types – If True, yield non-sequence basic types (int, float, str, bool).
- Return type:
Generator
[Tuple
[Any
,Any
,str
],None
,None
]
Examples
>>> # --- get all picks from a catalog object >>> import obsplus >>> import obspy.core.event as ev >>> cat = obsplus.load_dataset('bingham_test').event_client.get_events() >>> picks = [] # put all the picks in a list. >>> for pick, _, _ in yield_obj_parent_attr(cat, cls=ev.Pick): ... picks.append(pick) >>> assert len(picks)
>>> # --- yield all objects which have resource identifiers >>> objects = [] # list of (rid, parent) >>> RID = ev.ResourceIdentifier >>> for rid, parent, attr in yield_obj_parent_attr(cat, cls=RID): ... objects.append((str(rid), parent)) >>> assert len(objects)
>>> # --- Create a dict of {resource_id: [(attr, parent), ...]} >>> from collections import defaultdict >>> rid_mapping = defaultdict(list) >>> for rid, parent, attr in yield_obj_parent_attr(cat, cls=RID): ... rid_mapping[str(rid)].append((attr, parent)) >>> # count how many times each resource_id is referred to >>> count = {i: len(v) for i, v in rid_mapping.items()}