Skip to content

Commit

Permalink
Refactor common code for serializing references/literals
Browse files Browse the repository at this point in the history
  • Loading branch information
cthoyt committed Jan 21, 2025
1 parent 1266b38 commit ad0226d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 22 deletions.
19 changes: 10 additions & 9 deletions src/pyobo/struct/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,15 +250,7 @@ def multi_reference_escape(

def comma_separate_references(elements: Iterable[Reference | OBOLiteral]) -> str:
"""Map a list to strings and make comma separated."""
parts = []
for element in elements:
match element:
case Reference():
parts.append(get_preferred_curie(element))
case OBOLiteral(value, _datatype, _language):
# TODO check datatype is URI
parts.append(value)
return ", ".join(parts)
return ", ".join(reference_or_literal_to_str(element) for element in elements)


def _ground_relation(relation_str: str) -> Reference | None:
Expand Down Expand Up @@ -343,3 +335,12 @@ def _reference_list_tag(
) -> Iterable[str]:
for reference in references:
yield f"{tag}: {reference_escape(reference, ontology_prefix=ontology_prefix, add_name_comment=True)}"


def reference_or_literal_to_str(x: Reference | OBOLiteral) -> str:
"""Get a string from a reference or literal."""
match x:
case Reference():
return get_preferred_curie(x)
case OBOLiteral(value, _, _):
return value
16 changes: 3 additions & 13 deletions src/pyobo/struct/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
default_reference,
get_preferred_curie,
reference_escape,
reference_or_literal_to_str,
)
from .struct_utils import (
Annotation,
Expand Down Expand Up @@ -341,14 +342,7 @@ def extend_parents(self, references: Collection[Reference]) -> None:

def get_property_literals(self, prop: ReferenceHint) -> list[str]:
"""Get properties from the given key."""
rv = []
for t in self.properties.get(_ensure_ref(prop), []):
match t:
case Reference():
rv.append(get_preferred_curie(t))
case OBOLiteral(value, _datatype, _language):
rv.append(value)
return rv
return [reference_or_literal_to_str(t) for t in self.properties.get(_ensure_ref(prop), [])]

def get_property(self, prop: ReferenceHint) -> str | None:
"""Get a single property of the given key."""
Expand Down Expand Up @@ -1548,11 +1542,7 @@ def iterate_filtered_properties(
for t in term.get_property_annotations():
if t.predicate != prop:
continue
match t.value:
case OBOLiteral(value, _datatype):
yield term, value
case Reference():
yield term, get_preferred_curie(t.value)
yield term, reference_or_literal_to_str(t.value)

def get_filtered_properties_df(
self, prop: ReferenceHint, *, use_tqdm: bool = False
Expand Down

0 comments on commit ad0226d

Please sign in to comment.