Skip to content

Commit 82db8fc

Browse files
committed
refactor: Update type imports to use collections.abc for better clarity and consistency
1 parent a749847 commit 82db8fc

19 files changed

+87
-90
lines changed

meshed/base.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from collections import Counter
66
from dataclasses import dataclass, field, fields
77
from functools import partial, cached_property
8-
from typing import Callable, MutableMapping, Iterable, Union, Sized, Sequence, Literal
8+
from typing import Union, Literal
9+
from collections.abc import Callable, MutableMapping, Iterable, Sized, Sequence
910

1011
from i2 import Sig, call_somewhat_forgivingly
1112
from i2.signatures import (
@@ -782,7 +783,7 @@ def _mapped_extraction(src: dict, to_extract: dict):
782783
yield desired_name, src[src_name]
783784

784785

785-
def duplicates(elements: Union[Iterable, Sized]):
786+
def duplicates(elements: Iterable | Sized):
786787
c = Counter(elements)
787788
if len(c) != len(elements):
788789
return [name for name, count in c.items() if count > 1]
@@ -835,17 +836,18 @@ def _complete_dict_with_iterable_of_required_keys(
835836
to_complete[required_key] = required_key
836837

837838

838-
from typing import NewType, Dict, Tuple, Mapping
839+
from typing import NewType, Dict, Tuple
840+
from collections.abc import Mapping
839841

840842
# TODO: Make a type where ``isinstance(s, Identifier) == s.isidentifier()``
841843
Identifier = NewType("Identifier", str) # + should satisfy str.isidentifier
842844
Bind = Union[
843845
str, # Identifier or ' '.join(Iterable[Identifier])
844-
Dict[Identifier, Identifier],
845-
Sequence[Union[Identifier, Tuple[Identifier, Identifier]]],
846+
dict[Identifier, Identifier],
847+
Sequence[Union[Identifier, tuple[Identifier, Identifier]]],
846848
]
847849

848-
IdentifierMapping = Dict[Identifier, Identifier]
850+
IdentifierMapping = dict[Identifier, Identifier]
849851

850852

851853
def identifier_mapping(x: Bind) -> IdentifierMapping:

meshed/components.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
"""
44

55
from i2 import Sig
6-
from typing import Callable, Any
6+
from typing import Any
7+
from collections.abc import Callable
78
from operator import itemgetter, attrgetter
89
from dataclasses import dataclass
910
from functools import partial

meshed/composition.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
from dataclasses import fields
44
from inspect import signature
5-
from typing import Callable, Union
5+
from typing import Union
6+
from collections.abc import Callable
67
from functools import partial
78

89
from i2 import Sig, kwargs_trans
@@ -38,7 +39,7 @@ def func_node_kwargs_trans(func: Callable) -> FuncNodeKwargsTrans:
3839

3940

4041
def func_node_name_trans(
41-
name_trans: Callable[[str], Union[str, None]],
42+
name_trans: Callable[[str], str | None],
4243
*,
4344
also_apply_to_func_label: bool = False,
4445
):
@@ -68,7 +69,7 @@ def name_trans(name):
6869
# TODO: Extract ingress/egress boilerplate to wrapper
6970
def suffix_ids(
7071
func_nodes,
71-
renamer: Union[Renamer, str] = numbered_suffix_renamer,
72+
renamer: Renamer | str = numbered_suffix_renamer,
7273
*,
7374
also_apply_to_func_label: bool = False,
7475
):

meshed/dag.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,14 @@
138138
from itertools import chain
139139
from operator import attrgetter, eq
140140
from typing import (
141-
Callable,
142-
MutableMapping,
143141
Union,
144142
Optional,
145-
Iterable,
146143
Any,
147-
Mapping,
148144
Tuple,
149145
KT,
150146
VT,
151147
)
148+
from collections.abc import Callable, MutableMapping, Iterable, Mapping
152149
from warnings import warn
153150

154151
from i2 import double_up_as_factory, MultiFunc
@@ -201,7 +198,7 @@
201198

202199
from meshed.viz import dot_lines_of_objs, add_new_line_if_none
203200

204-
FuncMapping = Union[Mapping[KT, Callable], Iterable[Tuple[KT, Callable]]]
201+
FuncMapping = Union[Mapping[KT, Callable], Iterable[tuple[KT, Callable]]]
205202

206203

207204
def order_subset_from_list(items, sublist):
@@ -490,7 +487,7 @@ class DAG:
490487
491488
"""
492489

493-
func_nodes: Iterable[Union[FuncNode, Callable]] = ()
490+
func_nodes: Iterable[FuncNode | Callable] = ()
494491
cache_last_scope: bool = field(default=True, repr=False)
495492
parameter_merge: ParameterMerger = field(
496493
default=conservative_parameter_merge, repr=False
@@ -1163,7 +1160,7 @@ def params_for_src(self):
11631160
d[src_name].append(node.sig.parameters[arg_name])
11641161
return dict(d)
11651162

1166-
def src_name_params(self, src_names: Optional[Iterable[str]] = None):
1163+
def src_name_params(self, src_names: Iterable[str] | None = None):
11671164
"""Generate Parameter instances that are needed to compute ``src_names``"""
11681165
# see params_for_src property to see what d is
11691166
d = self.params_for_src
@@ -1613,7 +1610,7 @@ def dag():
16131610
return func_nodes_to_code(dag.func_nodes, dag.name)
16141611

16151612

1616-
def parametrized_dag_factory(dag: DAG, param_var_nodes: Union[str, Iterable[str]]):
1613+
def parametrized_dag_factory(dag: DAG, param_var_nodes: str | Iterable[str]):
16171614
"""
16181615
Constructs a factory for sub-DAGs derived from the input DAG, with values of
16191616
specific 'parameter' variable nodes precomputed and fixed. These precomputed nodes,
@@ -1794,7 +1791,7 @@ def ch_funcs(
17941791
func_nodes: DagAble = None,
17951792
*,
17961793
func_mapping: FuncMapping = (),
1797-
validate_func_mapping: Optional[FuncMappingValidator] = _validate_func_mapping,
1794+
validate_func_mapping: FuncMappingValidator | None = _validate_func_mapping,
17981795
# TODO: Design. Don't like the fact that ch_func_node_func needs a slot for
17991796
# func_comparator, which is then given later. Perhaps only ch_func_node_func should
18001797
# should be given (and it contains the func_comparator)

meshed/ext/gk.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# ---------- base --------------------------------------------------------------
1818

1919

20-
class Data(object):
20+
class Data:
2121
"""
2222
This wraps any data that is consumed or produced
2323
by a Operation. This data should also know how to serialize
@@ -145,7 +145,7 @@ def __repr__(self):
145145
"""
146146
Display more informative names for the Operation class
147147
"""
148-
return "%s(name='%s', needs=%s, provides=%s)" % (
148+
return "{}(name='{}', needs={}, provides={})".format(
149149
self.__class__.__name__,
150150
self.name,
151151
self.needs,
@@ -269,7 +269,7 @@ def __repr__(self):
269269
return 'DeleteInstruction("%s")' % self
270270

271271

272-
class Network(object):
272+
class Network:
273273
"""
274274
This is the main network implementation. The class contains all of the
275275
code necessary to weave together operations into a directed-acyclic-graph (DAG)
@@ -878,7 +878,7 @@ def __repr__(self):
878878
"""
879879
Display more informative names for the Operation class
880880
"""
881-
return "%s(name='%s', needs=%s, provides=%s, fn=%s)" % (
881+
return "{}(name='{}', needs={}, provides={}, fn={})".format(
882882
self.__class__.__name__,
883883
self.name,
884884
self.needs,
@@ -887,7 +887,7 @@ def __repr__(self):
887887
)
888888

889889

890-
class compose(object):
890+
class compose:
891891
"""
892892
This is a simple class that's used to compose ``operation`` instances into
893893
a computation graph.

meshed/itools.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,12 @@
55

66
from typing import (
77
Any,
8-
Mapping,
9-
Sized,
10-
MutableMapping,
11-
Iterable,
12-
Callable,
138
List,
149
TypeVar,
1510
Union,
1611
Optional,
1712
)
13+
from collections.abc import Mapping, Sized, MutableMapping, Iterable, Callable
1814
from itertools import product, chain
1915
from functools import wraps, reduce, partial
2016
from collections import defaultdict
@@ -28,7 +24,7 @@
2824
MutableGraph = MutableMapping[N, Iterable[N]]
2925

3026

31-
def _import_or_raise(module_name, pip_install_name: Optional[Union[str, bool]] = None):
27+
def _import_or_raise(module_name, pip_install_name: str | bool | None = None):
3228
try:
3329
return __import__(module_name)
3430
except ImportError as e:
@@ -345,7 +341,7 @@ def root_nodes(g: Graph):
345341

346342

347343
# TODO: Can be made much more efficient, by looking at the ancestors code itself
348-
def root_ancestors(graph: dict, nodes: Union[str, Iterable[str]]):
344+
def root_ancestors(graph: dict, nodes: str | Iterable[str]):
349345
"""
350346
Returns the roots of the sub-dag that contribute to compute the given nodes.
351347
"""
@@ -425,7 +421,7 @@ def reverse_edges(g: Graph):
425421
yield from product(dst_nodes, src)
426422

427423

428-
def has_cycle(g: Graph) -> List[N]:
424+
def has_cycle(g: Graph) -> list[N]:
429425
"""
430426
Returns a list representing a cycle in the graph if any. An empty list indicates no cycle.
431427
@@ -653,7 +649,7 @@ def filter_dict_on_keys(d, condition):
653649

654650

655651
def nodes_of_graph(graph):
656-
return set([*graph.keys(), *graph.values()])
652+
return {*graph.keys(), *graph.values()}
657653

658654

659655
def subtract_subgraph(graph, subgraph):

meshed/makers.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -149,14 +149,11 @@
149149
from typing import (
150150
Tuple,
151151
Optional,
152-
Iterator,
153-
Iterable,
154152
TypeVar,
155-
Callable,
156153
Dict,
157-
Mapping,
158154
Union,
159155
)
156+
from collections.abc import Iterator, Iterable, Callable, Mapping
160157
from functools import partial
161158

162159

@@ -249,7 +246,7 @@ def parse_body(body, *, body_index=None):
249246

250247

251248
# Note: generalize? glom?
252-
def parse_assignment(body: ast.Assign, info=None) -> Tuple:
249+
def parse_assignment(body: ast.Assign, info=None) -> tuple:
253250
# TODO: Make this validation better (at least more help in raised error)
254251
# TODO: extract validating code out as validation functions?
255252
info = _ast_info_str(body)
@@ -430,7 +427,7 @@ def parse_steps(src):
430427

431428
def src_to_func_node_factory(
432429
src, exclude_names=None
433-
) -> Iterator[Union[FuncNode, FuncNodeFactory]]:
430+
) -> Iterator[FuncNode | FuncNodeFactory]:
434431
"""
435432
:param src: Callable or string of callable.
436433
:param exclude_names: Names to exclude when making func_nodes
@@ -454,7 +451,7 @@ def src_to_func_node_factory(
454451
# to make itself. Do we gain much over simply saying "factory, make yourself"?
455452
def dlft_factory_to_func(
456453
factory: partial,
457-
name_to_func_map: Optional[Dict[str, Callable]] = None,
454+
name_to_func_map: dict[str, Callable] | None = None,
458455
use_place_holder_fallback=True,
459456
):
460457
"""Get a function for the given factory, using"""
@@ -545,7 +542,7 @@ def code_to_fnodes(
545542
*,
546543
func_src: FuncSource = dlft_factory_to_func,
547544
use_place_holder_fallback=False,
548-
) -> Tuple[FuncNode]:
545+
) -> tuple[FuncNode]:
549546
"""Get func_nodes from src code"""
550547
func_src = _ensure_func_src(func_src, use_place_holder_fallback)
551548
# Pass on to _code_to_fnodes to get func nodes iterable needed to make DAG
@@ -593,10 +590,10 @@ def code_to_digraph(src):
593590
# from typing import Tuple, Iterable, Iterator
594591
# from meshed import FuncNode, code_to_dag, code_to_fnodes, DAG
595592

596-
extract_tokens = re.compile("\w+").findall
593+
extract_tokens = re.compile(r"\w+").findall
597594

598595

599-
def triples_to_fnodes(triples: Iterable[Tuple[str, str, str]]) -> Iterable[FuncNode]:
596+
def triples_to_fnodes(triples: Iterable[tuple[str, str, str]]) -> Iterable[FuncNode]:
600597
"""Converts an iterable of func call triples to an iterable of ``FuncNode``s.
601598
(Which in turn can be converted to a ``DAG``.)
602599
@@ -624,9 +621,9 @@ def triples_to_fnodes(triples: Iterable[Tuple[str, str, str]]) -> Iterable[FuncN
624621

625622

626623
def _triple_to_func_call_str(
627-
outputs: Union[str, Iterable[str]],
624+
outputs: str | Iterable[str],
628625
func_name: str,
629-
inputs: Union[str, Iterable[str]],
626+
inputs: str | Iterable[str],
630627
) -> str:
631628
"""Converts a `(outputs, func_name, inputs)` triple to a function call string.
632629
@@ -699,7 +696,7 @@ def lined_dag(funcs):
699696
return dag
700697

701698

702-
from typing import Callable, Mapping, Iterable
699+
from collections.abc import Callable, Mapping, Iterable
703700

704701
NamedFuncs = Mapping[str, Callable]
705702

meshed/scrap/annotations_to_meshes.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
"""
88

99
import typing
10-
from typing import Dict, Protocol, Callable, TypeVar, Any
10+
from typing import Dict, Protocol, TypeVar, Any
11+
from collections.abc import Callable
1112
from collections.abc import Callable as CallableGenericAlias
1213
from inspect import signature, Signature, Parameter
1314
from functools import wraps
@@ -75,7 +76,7 @@ def callable_annots_to_signature(
7576

7677

7778
def func_types_to_protocol(
78-
func_types: Dict[str, CallableGenericAlias],
79+
func_types: dict[str, CallableGenericAlias],
7980
name: str = None,
8081
*,
8182
mk_argname: MkArgname = try_annotation_name,
@@ -102,7 +103,8 @@ def method_stub(*args, **kwargs):
102103

103104

104105
def test_func_types_to_protocol():
105-
from typing import Iterable, Any, NewType, Callable
106+
from typing import Any, NewType
107+
from collections.abc import Iterable, Callable
106108

107109
Group = NewType("Group", str)
108110
Item = NewType("Item", Any)
@@ -132,7 +134,7 @@ def items_for_group(self, group: Group) -> Iterable[Item]:
132134

133135

134136
def func_types_to_scaffold(
135-
func_types: Dict[str, CallableGenericAlias], name: str = None
137+
func_types: dict[str, CallableGenericAlias], name: str = None
136138
) -> str:
137139
"""Produces a scaffold class containing the said methods, with given annotations"""
138140

@@ -181,7 +183,8 @@ def items_for_group(self, group: Group) -> Iterable:
181183

182184

183185
def test_func_types_to_scaffold():
184-
from typing import Iterable, Any, NewType, Callable
186+
from typing import Any, NewType
187+
from collections.abc import Iterable, Callable
185188

186189
Group = NewType("Group", str)
187190
Item = NewType("Item", Any)

meshed/scrap/cached_dag.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Mapping
1+
from collections.abc import Mapping
22
from functools import partial
33
from collections import ChainMap
44
from meshed.itools import edge_reversed_graph, descendants

0 commit comments

Comments
 (0)