Skip to content

Commit

Permalink
fix: sort iterable before passing it to itertools.groupby() (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
jnussbaum authored Jul 18, 2024
1 parent d99c85c commit db8cb53
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion dsp_permissions_scripts/oap/oap_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ def _group_oaps_together(res_oaps: list[ResourceOap], val_oaps: list[ValueOap])
oaps: list[Oap] = []
deserialized_resource_iris = []

for res_iri, _val_oaps in itertools.groupby(val_oaps, key=lambda x: x.resource_iri):
def sort_algo(x: ValueOap) -> str:
"""
According to https://docs.python.org/3/library/itertools.html#itertools.groupby,
the iterable must be sorted on the same key function, before passing it to itertools.groupby().
"""
return x.resource_iri

for res_iri, _val_oaps in itertools.groupby(sorted(val_oaps, key=sort_algo), key=sort_algo):
res_oaps_filtered = [x for x in res_oaps if x.resource_iri == res_iri]
res_oap = res_oaps_filtered[0] if res_oaps_filtered else None
oaps.append(Oap(resource_oap=res_oap, value_oaps=sorted(_val_oaps, key=lambda x: x.value_iri)))
Expand Down

0 comments on commit db8cb53

Please sign in to comment.