Skip to content

Commit 633f3dc

Browse files
authored
Improve type hints (#489)
1 parent 31e13a2 commit 633f3dc

4 files changed

Lines changed: 35 additions & 41 deletions

File tree

src/pyobo/cli/lookup.py

Lines changed: 19 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import inspect
66
import json
7-
import sys
87
from collections.abc import Iterable, Mapping
98
from typing import TYPE_CHECKING
109

@@ -166,17 +165,27 @@ def typedefs(**kwargs: Unpack[LookupKwargs]) -> None:
166165
echo_df(df)
167166

168167

169-
def _help_page_mapping(id_to_name: Mapping[str, str], *, identifier: str | None = None) -> None:
168+
def _help_page_mapping(
169+
id_to_name: Mapping[str, str | list[str]], *, identifier: str | None = None
170+
) -> None:
170171
if not id_to_name:
171172
click.secho("no data", fg="red")
172173
elif identifier:
173174
value = id_to_name.get(identifier)
174-
if value:
175+
if isinstance(value, str):
175176
click.echo(value)
177+
elif isinstance(value, list):
178+
click.echo("\n".join(value))
176179
else:
177180
click.secho(f"no data for {identifier}", fg="red")
178181
else:
179-
click.echo_via_pager("\n".join("\t".join(item) for item in id_to_name.items()))
182+
click.echo_via_pager(
183+
"\n".join(
184+
f"{key}\t{value}"
185+
for key, values in id_to_name.items()
186+
for value in ([values] if isinstance(values, str) else values)
187+
)
188+
)
180189

181190

182191
@lookup_annotate
@@ -206,43 +215,24 @@ def synonyms(identifier: str | None, **kwargs: Unpack[LookupKwargs]) -> None:
206215
@click.option(
207216
"--relation", help="CURIE for the relationship or just the ID if local to the ontology"
208217
)
209-
@click.option("--target", help="Prefix for the target")
210218
@click.option("--summarize", is_flag=True)
211219
def relations(
212220
relation: str,
213-
target: str,
221+
target: str | None,
214222
summarize: bool,
215223
**kwargs: Unpack[LookupKwargs],
216224
) -> None:
217225
"""Page through the relations for entities in the given namespace."""
218-
import bioregistry
219-
220226
from ..api import get_filtered_relations_df, get_relations_df
221-
from ..struct.reference import _parse_str_or_curie_or_uri
222227

223228
if relation is None:
224229
relations_df = get_relations_df(**kwargs)
225-
if summarize:
226-
click.echo(relations_df[relations_df.columns[2]].value_counts())
227-
else:
228-
echo_df(relations_df)
229230
else:
230-
relation_reference = _parse_str_or_curie_or_uri(relation, strict=False)
231-
if relation_reference is None:
232-
click.secho(f"not a valid curie: {relation}", fg="red")
233-
raise sys.exit(1)
234-
235-
if target is not None:
236-
norm_target = bioregistry.normalize_prefix(target)
237-
if norm_target is None:
238-
raise ValueError
239-
relations_df = get_filtered_relations_df(
240-
relation=relation_reference,
241-
target=norm_target,
242-
**kwargs,
243-
)
244-
else:
245-
raise NotImplementedError(f"can not filter by target prefix {target}")
231+
relations_df = get_filtered_relations_df(relation=relation, **kwargs)
232+
if summarize:
233+
click.echo(relations_df[relations_df.columns[2]].value_counts())
234+
else:
235+
echo_df(relations_df)
246236

247237

248238
@lookup_annotate

src/pyobo/struct/functional/obo_to_functional.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ def get_ontology_axioms(obo_ontology: Obo) -> Iterable[f.Box]:
7878
used_has_scope = False
7979
for synonym_typedef in obo_ontology.synonym_typedefs:
8080
yield f.Declaration(synonym_typedef, type="AnnotationProperty")
81-
yield m.LabelMacro(synonym_typedef, synonym_typedef.name)
81+
if synonym_typedef.name is not None:
82+
yield m.LabelMacro(synonym_typedef, synonym_typedef.name)
8283
yield f.SubAnnotationPropertyOf(synonym_typedef, "oboInOwl:SynonymTypeProperty")
8384
if synonym_typedef.specificity:
8485
used_has_scope = True

src/pyobo/struct/reference.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,20 @@ def __eq__(self, other: Any) -> bool:
8686
return self.prefix == other.prefix and self.identifier == other.identifier
8787
raise TypeError
8888

89-
def __lt__(self, other: Referenced) -> bool:
90-
if not isinstance(other, curies.Reference | Referenced):
91-
raise TypeError
92-
return self.reference < other.reference
89+
def __lt__(self, other: curies.Reference | Referenced) -> bool:
90+
if isinstance(other, curies.Reference):
91+
return self.reference < other
92+
if isinstance(other, Referenced):
93+
return self.reference < other.reference
94+
raise TypeError
9395

9496
@property
95-
def prefix(self):
97+
def prefix(self) -> str:
9698
"""The prefix of the typedef."""
9799
return self.reference.prefix
98100

99101
@property
100-
def name(self):
102+
def name(self) -> str | None:
101103
"""The name of the typedef."""
102104
return self.reference.name
103105

src/pyobo/struct/struct.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,7 +1467,7 @@ def to_obonet(self: Obo, *, use_tqdm: bool = False) -> nx.MultiDiGraph:
14671467
)
14681468
return rv
14691469

1470-
def get_metadata(self) -> Mapping[str, Any]:
1470+
def get_metadata(self) -> dict[str, Any]:
14711471
"""Get metadata."""
14721472
return {
14731473
"version": self.data_version,
@@ -1568,14 +1568,14 @@ def get_typedef_df(self, use_tqdm: bool = False) -> pd.DataFrame:
15681568
]
15691569
return pd.DataFrame(rows, columns=["prefix", "identifier", "name"])
15701570

1571-
def iter_typedef_id_name(self) -> Iterable[tuple[str, str]]:
1571+
def iter_typedef_id_name(self) -> Iterable[tuple[str, str | None]]:
15721572
"""Iterate over typedefs' identifiers and their respective names."""
15731573
for typedef in self.typedefs or []:
15741574
yield typedef.identifier, typedef.name
15751575

15761576
def get_typedef_id_name_mapping(self) -> Mapping[str, str]:
15771577
"""Get a mapping from typedefs' identifiers to names."""
1578-
return dict(self.iter_typedef_id_name())
1578+
return {identifier: name for identifier, name in self.iter_typedef_id_name() if name}
15791579

15801580
#########
15811581
# PROPS #
@@ -1906,11 +1906,12 @@ def get_relation_multimapping(
19061906

19071907
def get_id_multirelations_mapping(
19081908
self,
1909-
typedef: TypeDef,
1909+
typedef: ReferenceHint,
19101910
*,
19111911
use_tqdm: bool = False,
19121912
) -> Mapping[str, list[Reference]]:
19131913
"""Get a mapping from identifiers to a list of all references for the given relation."""
1914+
typedef = _ensure_ref(typedef, ontology_prefix=self.ontology)
19141915
return multidict(
19151916
(stanza.identifier, reference)
19161917
for stanza in self._iter_stanzas(
@@ -2030,7 +2031,7 @@ def get_literal_mappings_df(self) -> pd.DataFrame:
20302031

20312032
def iterate_mapping_rows(
20322033
self, *, use_tqdm: bool = False
2033-
) -> Iterable[tuple[str, str, str, str, str, float | None, str | None]]:
2034+
) -> Iterable[tuple[str, str | None, str, str, str, float | None, str | None]]:
20342035
"""Iterate over SSSOM rows for mappings."""
20352036
for stanza in self._iter_stanzas(use_tqdm=use_tqdm):
20362037
for predicate, obj_ref, context in stanza.get_mappings(

0 commit comments

Comments
 (0)