Skip to content

Commit 9cdcf06

Browse files
committed
pre-commit: pyupgrade with __future__.annotations
1 parent db12684 commit 9cdcf06

File tree

8 files changed

+68
-64
lines changed

8 files changed

+68
-64
lines changed

.pre-commit-config.yaml

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1+
default_language_version:
2+
python: python3
13
repos:
24
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.0.1
5+
rev: v4.1.0
46
hooks:
57
- id: check-merge-conflict
68
- id: debug-statements
79
- id: mixed-line-ending
810
- id: check-case-conflict
911
- id: check-yaml
12+
- repo: https://github.com/asottile/pyupgrade
13+
rev: v2.31.0
14+
hooks:
15+
- id: pyupgrade
16+
args: [--py37-plus]
1017
- repo: https://github.com/timothycrosley/isort
11-
rev: 5.9.3
18+
rev: 5.10.1
1219
hooks:
1320
- id: isort
1421
- repo: https://github.com/python/black
15-
rev: 21.10b0
22+
rev: 22.1.0
1623
hooks:
1724
- id: black
18-
language_version: python3
1925
- repo: https://gitlab.com/pycqa/flake8
2026
rev: 3.9.2
2127
hooks:
2228
- id: flake8
23-
language_version: python3
2429
- repo: https://github.com/pre-commit/mirrors-mypy
25-
rev: v0.910-1
30+
rev: v0.931
2631
hooks:
2732
- id: mypy
2833
args: ["--strict", "--show-error-codes"]

nxontology/imports.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
from __future__ import annotations
2+
13
import logging
24
from datetime import date
35
from os import PathLike
4-
from typing import AnyStr, BinaryIO, Counter, List, Optional, Tuple, Union, cast
6+
from typing import AnyStr, BinaryIO, Counter, cast
57

68
import networkx as nx
79
from pronto import Ontology as Prontology # type: ignore [attr-defined]
@@ -70,7 +72,7 @@ def from_obo_library(slug: str) -> NXOntology[str]:
7072
return nxo
7173

7274

73-
def from_file(handle: Union[BinaryIO, str, "PathLike[AnyStr]"]) -> NXOntology[str]:
75+
def from_file(handle: BinaryIO | str | PathLike[AnyStr]) -> NXOntology[str]:
7476
"""
7577
Read ontology in OBO, OWL, or JSON (OBO Graphs) format via pronto.
7678
@@ -84,7 +86,7 @@ def from_file(handle: Union[BinaryIO, str, "PathLike[AnyStr]"]) -> NXOntology[st
8486

8587
def _pronto_edges_for_term(
8688
term: Term, default_rel_type: str = "is a"
87-
) -> List[Tuple[Node, Node, str]]:
89+
) -> list[tuple[Node, Node, str]]:
8890
"""
8991
Extract edges including "is a" relationships for a Pronto term.
9092
https://github.com/althonos/pronto/issues/119#issuecomment-956541286
@@ -158,7 +160,7 @@ def pronto_to_multidigraph(
158160

159161
def multidigraph_to_digraph(
160162
graph: nx.MultiDiGraph,
161-
rel_types: Optional[List[str]] = None,
163+
rel_types: list[str] | None = None,
162164
reverse: bool = True,
163165
reduce: bool = False,
164166
) -> nx.DiGraph:
@@ -216,7 +218,8 @@ def multidigraph_to_digraph(
216218
def read_gene_ontology(
217219
release: str = "current",
218220
source_file: str = "go-basic.json.gz",
219-
rel_types: Optional[List[str]] = [
221+
rel_types: list[str]
222+
| None = [
220223
"is a",
221224
"part of",
222225
"regulates",

nxontology/node.py

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,7 @@
22

33
import math
44
import warnings
5-
from typing import (
6-
TYPE_CHECKING,
7-
Any,
8-
Dict,
9-
Generic,
10-
Hashable,
11-
Iterator,
12-
List,
13-
Optional,
14-
Set,
15-
TypeVar,
16-
)
5+
from typing import TYPE_CHECKING, Any, Generic, Hashable, Iterator, TypeVar
176

187
import networkx as nx
198

@@ -37,7 +26,7 @@ class Node_Info(Freezable, Generic[Node]):
3726
without requiring an external corpus to ascertain term frequency.
3827
"""
3928

40-
ic_metrics: List[str] = [
29+
ic_metrics: list[str] = [
4130
"intrinsic_ic",
4231
"intrinsic_ic_sanchez",
4332
]
@@ -53,7 +42,7 @@ def __init__(self, nxo: NXOntology[Node], node: Node):
5342
self.node = node
5443

5544
@property
56-
def name(self) -> Optional[str]:
45+
def name(self) -> str | None:
5746
"""Human readable name / label."""
5847
value = self._get_node_attribute(
5948
custom_field="node_name_attribute", default="name"
@@ -66,7 +55,7 @@ def name(self) -> Optional[str]:
6655
return None if value is None else str(value)
6756

6857
@property
69-
def label(self) -> Optional[str]:
58+
def label(self) -> str | None:
7059
"""Human readable node name / label."""
7160
warnings.warn(
7261
"Node_Info.label is deprecated and will be removed. Use Node_Info.name instead.",
@@ -76,14 +65,14 @@ def label(self) -> Optional[str]:
7665
return self.name
7766

7867
@property
79-
def identifier(self) -> Optional[Any]:
68+
def identifier(self) -> Any | None:
8069
"""Database / machine identifier."""
8170
return self._get_node_attribute(
8271
custom_field="node_identifier_attribute", default="identifier"
8372
)
8473

8574
@property
86-
def url(self) -> Optional[str]:
75+
def url(self) -> str | None:
8776
"""Uniform Resource Locator (URL)"""
8877
value = self._get_node_attribute(
8978
custom_field="node_url_attribute", default="url"
@@ -102,19 +91,19 @@ def frozen(self) -> bool:
10291
return self.nxo.frozen
10392

10493
@property
105-
def data(self) -> Dict[Any, Any]:
94+
def data(self) -> dict[Any, Any]:
10695
"""Dictionary of node data (properties) for `self.node` in the networkx graph."""
10796
data = self.nxo.graph.nodes[self.node]
10897
assert isinstance(data, dict)
10998
return data
11099

111100
@property
112-
def parents(self) -> Set[Node]:
101+
def parents(self) -> set[Node]:
113102
"""Direct parent nodes of this node."""
114103
return set(self.nxo.graph.predecessors(self.node))
115104

116105
@property
117-
def parent(self) -> Optional[Node]:
106+
def parent(self) -> Node | None:
118107
"""
119108
Sole parent of this node, or None if this node is a root.
120109
If this node has multiple parents, raise ValueError.
@@ -129,13 +118,13 @@ def parent(self) -> Optional[Node]:
129118
raise ValueError(f"Node {self!r} has multiple parents.")
130119

131120
@property
132-
def children(self) -> Set[Node]:
121+
def children(self) -> set[Node]:
133122
"""Direct child nodes of this node."""
134123
return set(self.nxo.graph.successors(self.node))
135124

136125
@property # type: ignore [misc]
137126
@cache_on_frozen
138-
def ancestors(self) -> Set[Node]:
127+
def ancestors(self) -> set[Node]:
139128
"""
140129
Get ancestors of node in graph, including the node itself.
141130
Ancestors refers to more general concepts in an ontology,
@@ -148,7 +137,7 @@ def ancestors(self) -> Set[Node]:
148137

149138
@property # type: ignore [misc]
150139
@cache_on_frozen
151-
def descendants(self) -> Set[Node]:
140+
def descendants(self) -> set[Node]:
152141
"""
153142
Get descendants of node in graph, including the node itself.
154143
Descendants refers to more specific concepts in an ontology,
@@ -171,12 +160,12 @@ def n_descendants(self) -> int:
171160

172161
@property # type: ignore [misc]
173162
@cache_on_frozen
174-
def roots(self) -> Set[Node]:
163+
def roots(self) -> set[Node]:
175164
"""Ancestors of this node that are roots (top-level)."""
176165
return self.ancestors & self.nxo.roots
177166

178167
@property
179-
def leaves(self) -> Set[Node]:
168+
def leaves(self) -> set[Node]:
180169
"""Descendents of this node that are leaves."""
181170
return self.descendants & self.nxo.leaves
182171

nxontology/ontology.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import itertools
44
import json
55
import logging
6-
from typing import Any, Dict, Generic, Iterable, List, Optional, Set, cast
6+
from typing import Any, Generic, Iterable, cast
77

88
import fsspec
99
import networkx as nx
@@ -28,10 +28,10 @@ class NXOntology(Freezable, Generic[Node]):
2828
Edges should go from general to more specific.
2929
"""
3030

31-
def __init__(self, graph: Optional[nx.DiGraph] = None):
31+
def __init__(self, graph: nx.DiGraph | None = None):
3232
self.graph = nx.DiGraph(graph)
3333
self.check_is_dag()
34-
self._node_info_cache: Dict[Node, Node_Info[Node]] = {}
34+
self._node_info_cache: dict[Node, Node_Info[Node]] = {}
3535

3636
def check_is_dag(self) -> None:
3737
if nx.is_directed_acyclic_graph(self.graph):
@@ -46,7 +46,7 @@ def check_is_dag(self) -> None:
4646
)
4747

4848
@property
49-
def name(self) -> Optional[str]:
49+
def name(self) -> str | None:
5050
"""Short human-readable name for the ontology."""
5151
key = self.graph.graph.get("graph_name_attribute", "name")
5252
name = self.graph.graph.get(key)
@@ -101,7 +101,7 @@ def add_edge(self, u_of_edge: Node, v_of_edge: Node, **attr: Any) -> None:
101101

102102
@property # type: ignore [misc]
103103
@cache_on_frozen
104-
def roots(self) -> Set[Node]:
104+
def roots(self) -> set[Node]:
105105
"""
106106
Return all top-level nodes, including isolates.
107107
"""
@@ -127,7 +127,7 @@ def root(self) -> Node:
127127

128128
@property # type: ignore [misc]
129129
@cache_on_frozen
130-
def leaves(self) -> Set[Node]:
130+
def leaves(self) -> set[Node]:
131131
"""
132132
Return all bottom-level nodes, including isolates.
133133
"""
@@ -139,7 +139,7 @@ def leaves(self) -> Set[Node]:
139139

140140
@property # type: ignore [misc]
141141
@cache_on_frozen
142-
def isolates(self) -> Set[Node]:
142+
def isolates(self) -> set[Node]:
143143
"""
144144
Return disconnected nodes.
145145
"""
@@ -172,8 +172,8 @@ def similarity_metrics(
172172
node_0: Node,
173173
node_1: Node,
174174
ic_metric: str = "intrinsic_ic_sanchez",
175-
keys: Optional[List[str]] = None,
176-
) -> Dict[str, Any]:
175+
keys: list[str] | None = None,
176+
) -> dict[str, Any]:
177177
"""
178178
Compute intrinsic similarity metrics for two nodes.
179179
"""
@@ -184,8 +184,8 @@ def compute_similarities(
184184
self,
185185
source_nodes: Iterable[Node],
186186
target_nodes: Iterable[Node],
187-
ic_metrics: List[str] = ["intrinsic_ic_sanchez"],
188-
) -> Iterable[Dict[str, Any]]:
187+
ic_metrics: list[str] = ["intrinsic_ic_sanchez"],
188+
) -> Iterable[dict[str, Any]]:
189189
"""
190190
Yield similarity metric dictionaries for all combinations of
191191
source_node-target_node-ic_metric.
@@ -251,10 +251,10 @@ def n_edges(self) -> int:
251251
def set_graph_attributes(
252252
self,
253253
*,
254-
graph_name_attribute: Optional[str] = None,
255-
node_name_attribute: Optional[str] = None,
256-
node_identifier_attribute: Optional[str] = None,
257-
node_url_attribute: Optional[str] = None,
254+
graph_name_attribute: str | None = None,
255+
node_name_attribute: str | None = None,
256+
node_identifier_attribute: str | None = None,
257+
node_url_attribute: str | None = None,
258258
) -> None:
259259
"""
260260
Convenience method to set attributes on the graph that are recognized by nxontology.

nxontology/similarity.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import math
4-
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, Set, Tuple
4+
from typing import TYPE_CHECKING, Any, Generic
55

66
if TYPE_CHECKING:
77
from nxontology.ontology import NXOntology
@@ -49,12 +49,12 @@ def node_1_subsumes_0(self) -> bool:
4949

5050
@property # type: ignore [misc]
5151
@cache_on_frozen
52-
def common_ancestors(self) -> Set[Node]:
52+
def common_ancestors(self) -> set[Node]:
5353
return self.info_0.ancestors & self.info_1.ancestors
5454

5555
@property # type: ignore [misc]
5656
@cache_on_frozen
57-
def union_ancestors(self) -> Set[Node]:
57+
def union_ancestors(self) -> set[Node]:
5858
return self.info_0.ancestors | self.info_1.ancestors
5959

6060
@property
@@ -91,7 +91,7 @@ def batet_log(self) -> float:
9191
# replace negative sign with abs to avoid returning -0.0.
9292
return abs(math.log(1 - self.batet) / math.log(self.n_union_ancestors))
9393

94-
def results(self, keys: Optional[List[str]] = None) -> Dict[str, Any]:
94+
def results(self, keys: list[str] | None = None) -> dict[str, Any]:
9595
if keys is None:
9696
keys = self.default_results
9797
return {key: getattr(self, key) for key in keys}
@@ -155,7 +155,7 @@ def node_1_ic_scaled(self) -> float:
155155

156156
@property # type: ignore [misc]
157157
@cache_on_frozen
158-
def _resnik_mica(self) -> Tuple[float, Optional[Node]]:
158+
def _resnik_mica(self) -> tuple[float, Node | None]:
159159
if not self.common_ancestors:
160160
return 0.0, None
161161
resnik, mica = max(
@@ -166,7 +166,7 @@ def _resnik_mica(self) -> Tuple[float, Optional[Node]]:
166166
return resnik, mica
167167

168168
@property
169-
def mica(self) -> Optional[Node]:
169+
def mica(self) -> Node | None:
170170
"""
171171
Most informative common ancestor.
172172
None if no common ancestors exist.

nxontology/utils.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import annotations
2+
13
import abc
24
import functools
3-
from typing import Callable, Dict, TypeVar
5+
from typing import Callable, TypeVar
46

57

68
class Freezable(abc.ABC):
@@ -30,9 +32,9 @@ def wrapped(self: T_Freezable) -> T:
3032
if not self.frozen:
3133
return func(self)
3234
try:
33-
method_cache: Dict[str, T] = getattr(self, "__method_cache")
35+
method_cache: dict[str, T] = getattr(self, "__method_cache")
3436
except AttributeError:
35-
method_cache: Dict[str, T] = {} # type: ignore [no-redef]
37+
method_cache: dict[str, T] = {} # type: ignore [no-redef]
3638
setattr(self, "__method_cache", method_cache)
3739
if fname not in method_cache:
3840
method_cache[fname] = func(self)

0 commit comments

Comments
 (0)