Skip to content

Commit f158384

Browse files
authored
fix(hugr-py): more ruff lints + fix some typos (#1246)
import ruff.toml from guppylang - turn on more lints - mostly auto fixes, mostly import sorting add a config file for `typos` tool https://github.com/crate-ci/typos?tab=readme-ov-file - we could consider adding this to CI/pre-commit but don't want to do a big repo-wide change right now - I used cli typos tool with `cargo install typos-cli` coverage is not happy because most of the fixes are in TYPE_CHECKING import blocks or unraised exceptions
1 parent 7dadadf commit f158384

25 files changed

+297
-145
lines changed

_typos.toml

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[default.extend-identifiers]
2+
bck = "bck" # BiMap uses abbreviation
3+
ser_it = "ser_it"
4+
SerCollection = "SerCollection"

hugr-py/src/hugr/cfg.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass
4+
from typing import TYPE_CHECKING
45

56
import hugr.ops as ops
7+
import hugr.val as val
68

79
from .dfg import _DfBase
8-
from .exceptions import NoSiblingAncestor, NotInSameCfg, MismatchedExit
10+
from .exceptions import MismatchedExit, NoSiblingAncestor, NotInSameCfg
911
from .hugr import Hugr, ParentBuilder
10-
from .node_port import Node, Wire, ToNode
11-
from .tys import TypeRow, Type
12-
import hugr.val as val
12+
13+
if TYPE_CHECKING:
14+
from .node_port import Node, ToNode, Wire
15+
from .tys import Type, TypeRow
1316

1417

1518
class Block(_DfBase[ops.DataflowBlock]):
@@ -27,13 +30,13 @@ def _wire_up_port(self, node: Node, offset: int, p: Wire) -> Type:
2730
src_parent = self.hugr[src.node].parent
2831
try:
2932
super()._wire_up_port(node, offset, p)
30-
except NoSiblingAncestor:
33+
except NoSiblingAncestor as e:
3134
# note this just checks if there is a common CFG ancestor
3235
# it does not check for valid dominance between basic blocks
3336
# that is deferred to full HUGR validation.
3437
while cfg_node != src_parent:
3538
if src_parent is None or src_parent == self.hugr.root:
36-
raise NotInSameCfg(src.node.idx, node.idx)
39+
raise NotInSameCfg(src.node.idx, node.idx) from e
3740
src_parent = self.hugr[src_parent].parent
3841

3942
self.hugr.add_link(src, node.inp(offset))

hugr-py/src/hugr/cond_loop.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass
4+
from typing import TYPE_CHECKING
45

56
import hugr.ops as ops
67

78
from .dfg import _DfBase
89
from .hugr import Hugr, ParentBuilder
9-
from .node_port import Node, Wire, ToNode
1010

11-
from .tys import Sum, TypeRow
11+
if TYPE_CHECKING:
12+
from .node_port import Node, ToNode, Wire
13+
from .tys import Sum, TypeRow
1214

1315

1416
class Case(_DfBase[ops.Case]):
@@ -35,7 +37,8 @@ def __init__(self, case: Case) -> None:
3537

3638
def _parent_conditional(self) -> Conditional:
3739
if self._parent_cond is None:
38-
raise ConditionalError("If must have a parent conditional.")
40+
msg = "If must have a parent conditional."
41+
raise ConditionalError(msg)
3942
return self._parent_cond
4043

4144

@@ -84,11 +87,13 @@ def _update_outputs(self, outputs: TypeRow) -> None:
8487
self.parent_op._outputs = outputs
8588
else:
8689
if outputs != self.parent_op._outputs:
87-
raise ConditionalError("Mismatched case outputs.")
90+
msg = "Mismatched case outputs."
91+
raise ConditionalError(msg)
8892

8993
def add_case(self, case_id: int) -> Case:
9094
if case_id not in self.cases:
91-
raise ConditionalError(f"Case {case_id} out of possible range.")
95+
msg = f"Case {case_id} out of possible range."
96+
raise ConditionalError(msg)
9297
input_types = self.parent_op.nth_inputs(case_id)
9398
new_case = Case.new_nested(
9499
ops.Case(input_types),

hugr-py/src/hugr/dfg.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
from dataclasses import dataclass, replace
44
from typing import (
55
TYPE_CHECKING,
6-
Iterable,
7-
Sequence,
86
TypeVar,
97
)
108

@@ -13,23 +11,25 @@
1311
import hugr.ops as ops
1412
import hugr.val as val
1513
from hugr.tys import (
14+
ExtensionSet,
15+
FunctionKind,
16+
FunctionType,
17+
PolyFuncType,
1618
Type,
19+
TypeArg,
1720
TypeRow,
1821
get_first_sum,
19-
FunctionType,
20-
TypeArg,
21-
FunctionKind,
22-
PolyFuncType,
23-
ExtensionSet,
2422
)
2523

2624
from .exceptions import NoSiblingAncestor
2725
from .hugr import Hugr, ParentBuilder
28-
from .node_port import Node, OutPort, Wire, ToNode
2926

3027
if TYPE_CHECKING:
28+
from collections.abc import Iterable, Sequence
29+
3130
from .cfg import Cfg
3231
from .cond_loop import Conditional, If, TailLoop
32+
from .node_port import Node, OutPort, ToNode, Wire
3333

3434

3535
DP = TypeVar("DP", bound=ops.DfParentOp)
@@ -210,7 +210,8 @@ def _fn_sig(self, func: ToNode) -> PolyFuncType:
210210
case FunctionKind(sig):
211211
signature = sig
212212
case _:
213-
raise ValueError("Expected 'func' to be a function")
213+
msg = "Expected 'func' to be a function"
214+
raise ValueError(msg)
214215
return signature
215216

216217
def _wire_up(self, node: Node, ports: Iterable[Wire]) -> TypeRow:
@@ -223,7 +224,8 @@ def _get_dataflow_type(self, wire: Wire) -> Type:
223224
port = wire.out_port()
224225
ty = self.hugr.port_type(port)
225226
if ty is None:
226-
raise ValueError(f"Port {port} is not a dataflow port.")
227+
msg = f"Port {port} is not a dataflow port."
228+
raise ValueError(msg)
227229
return ty
228230

229231
def _wire_up_port(self, node: Node, offset: int, p: Wire) -> Type:

hugr-py/src/hugr/exceptions.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ class NoSiblingAncestor(Exception):
88

99
@property
1010
def msg(self):
11-
return f"Source {self.src} has no sibling ancestor of target {self.tgt}, so cannot wire up."
11+
return (
12+
f"Source {self.src} has no sibling ancestor of target {self.tgt},"
13+
" so cannot wire up."
14+
)
1215

1316

1417
@dataclass
@@ -18,7 +21,10 @@ class NotInSameCfg(Exception):
1821

1922
@property
2023
def msg(self):
21-
return f"Source {self.src} is not in the same CFG as target {self.tgt}, so cannot wire up."
24+
return (
25+
f"Source {self.src} is not in the same CFG as target {self.tgt},"
26+
" so cannot wire up."
27+
)
2228

2329

2430
@dataclass

hugr-py/src/hugr/function.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass
4+
from typing import TYPE_CHECKING
45

56
import hugr.ops as ops
67
import hugr.val as val
78

89
from .dfg import _DfBase
9-
from hugr.node_port import Node
1010
from .hugr import Hugr
11-
from .tys import TypeRow, TypeParam, PolyFuncType, Type, TypeBound
11+
12+
if TYPE_CHECKING:
13+
from hugr.node_port import Node
14+
15+
from .tys import PolyFuncType, Type, TypeBound, TypeParam, TypeRow
1216

1317

1418
@dataclass

hugr-py/src/hugr/hugr.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
from __future__ import annotations
22

3-
from collections.abc import Mapping
3+
from collections.abc import Iterable, Mapping
44
from dataclasses import dataclass, field, replace
55
from typing import (
6+
TYPE_CHECKING,
67
Generic,
7-
Iterable,
88
Protocol,
99
TypeVar,
1010
cast,
1111
overload,
12-
Type as PyType,
1312
)
1413

15-
16-
from hugr.ops import Op, DataflowOp, Const, Call
17-
from hugr.tys import Type, Kind, ValueKind
18-
from hugr.val import Value
19-
from hugr.node_port import Direction, InPort, OutPort, ToNode, Node, _SubPort
14+
from hugr.node_port import Direction, InPort, Node, OutPort, ToNode, _SubPort
15+
from hugr.ops import Call, Const, DataflowOp, Op
2016
from hugr.serialization.ops import OpType as SerialOp
2117
from hugr.serialization.serial_hugr import SerialHugr
18+
from hugr.tys import Kind, Type, ValueKind
2219
from hugr.utils import BiMap
2320

2421
from .exceptions import ParentBeforeChild
2522

23+
if TYPE_CHECKING:
24+
from hugr.val import Value
25+
2626

2727
@dataclass()
2828
class NodeData:
@@ -88,7 +88,7 @@ def __iter__(self):
8888
def __len__(self) -> int:
8989
return self.num_nodes()
9090

91-
def _get_typed_op(self, node: ToNode, cl: PyType[OpVar2]) -> OpVar2:
91+
def _get_typed_op(self, node: ToNode, cl: type[OpVar2]) -> OpVar2:
9292
op = self[node].op
9393
assert isinstance(op, cl)
9494
return op
@@ -241,11 +241,11 @@ def incoming_links(self, node: ToNode) -> Iterable[tuple[InPort, list[OutPort]]]
241241
return self._node_links(node, self._links.bck)
242242

243243
def num_incoming(self, node: Node) -> int:
244-
# connecetd links
244+
# connected links
245245
return sum(1 for _ in self.incoming_links(node))
246246

247247
def num_outgoing(self, node: ToNode) -> int:
248-
# connecetd links
248+
# connected links
249249
return sum(1 for _ in self.outgoing_links(node))
250250

251251
# TODO: num_links and _linked_ports
@@ -274,7 +274,7 @@ def insert_hugr(self, hugr: Hugr, parent: ToNode | None = None) -> dict[Node, No
274274
mapping[node_data.parent] if node_data.parent else parent
275275
)
276276
except KeyError as e:
277-
raise ParentBeforeChild() from e
277+
raise ParentBeforeChild from e
278278
mapping[Node(idx)] = self.add_node(node_data.op, node_parent)
279279

280280
for src, dst in hugr._links.items():

hugr-py/src/hugr/node_port.py

+13-10
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,19 @@
33
from dataclasses import dataclass, field, replace
44
from enum import Enum
55
from typing import (
6+
TYPE_CHECKING,
67
ClassVar,
7-
Iterator,
8+
Generic,
89
Protocol,
9-
overload,
1010
TypeVar,
11-
Generic,
11+
overload,
1212
)
13+
1314
from typing_extensions import Self
1415

16+
if TYPE_CHECKING:
17+
from collections.abc import Iterator
18+
1519

1620
class Direction(Enum):
1721
INCOMING = 0
@@ -57,7 +61,7 @@ def __getitem__(
5761
) -> OutPort | Iterator[OutPort]:
5862
return self.to_node()._index(index)
5963

60-
def out_port(self) -> "OutPort":
64+
def out_port(self) -> OutPort:
6165
return OutPort(self.to_node(), 0)
6266

6367
def inp(self, offset: int) -> InPort:
@@ -83,17 +87,16 @@ def _index(
8387
) -> OutPort | Iterator[OutPort]:
8488
match index:
8589
case int(index):
86-
if self._num_out_ports is not None:
87-
if index >= self._num_out_ports:
88-
raise IndexError("Index out of range")
90+
if self._num_out_ports is not None and index >= self._num_out_ports:
91+
msg = "Index out of range"
92+
raise IndexError(msg)
8993
return self.out(index)
9094
case slice():
9195
start = index.start or 0
9296
stop = index.stop or self._num_out_ports
9397
if stop is None:
94-
raise ValueError(
95-
"Stop must be specified when number of outputs unknown"
96-
)
98+
msg = "Stop must be specified when number of outputs unknown"
99+
raise ValueError(msg)
97100
step = index.step or 1
98101
return (self[i] for i in range(start, stop, step))
99102
case tuple(xs):

hugr-py/src/hugr/ops.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass, field
4-
from typing import Protocol, Sequence, runtime_checkable, TypeVar
5-
from hugr.serialization.ops import BaseOp
4+
from typing import TYPE_CHECKING, Protocol, TypeVar, runtime_checkable
5+
66
import hugr.serialization.ops as sops
7-
from hugr.utils import ser_it
87
import hugr.tys as tys
9-
from hugr.node_port import Node, InPort, OutPort, Wire
108
import hugr.val as val
9+
from hugr.node_port import InPort, Node, OutPort, Wire
10+
from hugr.utils import ser_it
11+
12+
if TYPE_CHECKING:
13+
from collections.abc import Sequence
14+
15+
from hugr.serialization.ops import BaseOp
1116

1217

1318
@dataclass
@@ -616,11 +621,13 @@ def _fn_instantiation(
616621
else:
617622
# TODO substitute type args into signature to get instantiation
618623
if instantiation is None:
619-
raise NoConcreteFunc("Missing instantiation for polymorphic function.")
624+
msg = "Missing instantiation for polymorphic function."
625+
raise NoConcreteFunc(msg)
620626
type_args = type_args or []
621627

622628
if len(signature.params) != len(type_args):
623-
raise NoConcreteFunc("Mismatched number of type arguments.")
629+
msg = "Mismatched number of type arguments."
630+
raise NoConcreteFunc(msg)
624631
return instantiation, list(type_args)
625632

626633

Original file line numberDiff line numberDiff line change
@@ -1,3 +0,0 @@
1-
from .serial_hugr import SerialHugr
2-
3-
__all__ = ["SerialHugr"]

0 commit comments

Comments
 (0)