Skip to content

Commit 6ff2a37

Browse files
authored
refactor: remove implement_pretty_repr() layer (#154)
* ci: remove outdated VSCode settings * ci: run pytest non-verbose in VSCode (verbose is a bit slower) * ci: switch to VSCode telemetry.telemetryLevel settings * docs: abbreviate type hints with autodoc_typehints_format * docs: sort API by position in the source code
1 parent c743249 commit 6ff2a37

File tree

8 files changed

+47
-58
lines changed

8 files changed

+47
-58
lines changed

.vscode/settings.json

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@
3737
"**/.tox/**": true
3838
},
3939
"git.rebaseWhenSync": true,
40-
"githubPullRequests.telemetry.enabled": false,
41-
"gitlens.advanced.telemetry.enabled": false,
4240
"json.schemas": [
4341
{
4442
"fileMatch": ["*particle*.json"],
@@ -52,7 +50,6 @@
5250
"python.analysis.autoImportCompletions": false,
5351
"python.analysis.diagnosticMode": "workspace",
5452
"python.formatting.provider": "black",
55-
"python.languageServer": "Pylance",
5653
"python.linting.banditEnabled": false,
5754
"python.linting.enabled": true,
5855
"python.linting.flake8Enabled": true,
@@ -61,9 +58,7 @@
6158
"python.linting.pylamaEnabled": false,
6259
"python.linting.pylintCategorySeverity.refactor": "Information",
6360
"python.linting.pylintEnabled": true,
64-
"python.linting.pylintUseMinimalCheckers": false,
65-
"python.testing.nosetestsEnabled": false,
66-
"python.testing.pytestArgs": ["--color=no", "--no-cov", "-vv"],
61+
"python.testing.pytestArgs": ["--color=no", "--no-cov"],
6762
"python.testing.pytestEnabled": true,
6863
"python.testing.unittestEnabled": false,
6964
"rewrap.wrappingColumn": 79,
@@ -72,8 +67,7 @@
7267
"*/.pydocstyle": true,
7368
".constraints/*.txt": true
7469
},
75-
"telemetry.enableCrashReporter": false,
76-
"telemetry.enableTelemetry": false,
70+
"telemetry.telemetryLevel": "off",
7771
"yaml.schemas": {
7872
"./src/qrules/particle-validation.json": ["*particle*.y*ml"],
7973
"https://raw.githubusercontent.com/readthedocs/readthedocs.org/master/readthedocs/rtd_tests/fixtures/spec/v2/schema.yml": ".readthedocs.yml"

docs/conf.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@ def fetch_logo(url: str, output_path: str) -> None:
174174
]
175175
),
176176
}
177+
autodoc_member_order = "bysource"
178+
autodoc_typehints_format = "short"
177179
codeautolink_concat_default = True
178180
AUTODOC_INSERT_SIGNATURE_LINEBREAKS = True
179181
graphviz_output_format = "svg"

src/qrules/_implementers.py

Lines changed: 29 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""A collection of implementation tools to can be used accross all modules."""
22

3-
from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar
3+
from typing import TYPE_CHECKING, Any, Type, TypeVar
44

55
import attrs
66

@@ -14,39 +14,32 @@
1414
_DecoratedClass = TypeVar("_DecoratedClass")
1515

1616

17-
def implement_pretty_repr() -> Callable[
18-
[Type[_DecoratedClass]], Type[_DecoratedClass]
19-
]:
17+
def implement_pretty_repr(
18+
decorated_class: Type[_DecoratedClass],
19+
) -> Type[_DecoratedClass]:
2020
"""Implement a pretty :code:`repr` in a class decorated by `attrs`."""
21-
22-
def decorator(
23-
decorated_class: Type[_DecoratedClass],
24-
) -> Type[_DecoratedClass]:
25-
if not attrs.has(decorated_class):
26-
raise TypeError(
27-
"Can only implement a pretty repr for a class created with"
28-
" attrs"
29-
)
30-
31-
def repr_pretty(self: Any, p: "PrettyPrinter", cycle: bool) -> None:
32-
class_name = type(self).__name__
33-
if cycle:
34-
p.text(f"{class_name}(...)")
35-
else:
36-
with p.group(indent=2, open=f"{class_name}("):
37-
for field in attrs.fields(type(self)):
38-
if not field.init:
39-
continue
40-
value = getattr(self, field.name)
41-
p.breakable()
42-
p.text(f"{field.name}=")
43-
p.pretty(value)
44-
p.text(",")
45-
p.breakable()
46-
p.text(")")
47-
48-
# pylint: disable=protected-access
49-
decorated_class._repr_pretty_ = repr_pretty # type: ignore[attr-defined]
50-
return decorated_class
51-
52-
return decorator
21+
if not attrs.has(decorated_class):
22+
raise TypeError(
23+
"Can only implement a pretty repr for a class created with attrs"
24+
)
25+
26+
def repr_pretty(self: Any, p: "PrettyPrinter", cycle: bool) -> None:
27+
class_name = type(self).__name__
28+
if cycle:
29+
p.text(f"{class_name}(...)")
30+
else:
31+
with p.group(indent=2, open=f"{class_name}("):
32+
for field in attrs.fields(type(self)):
33+
if not field.init:
34+
continue
35+
value = getattr(self, field.name)
36+
p.breakable()
37+
p.text(f"{field.name}=")
38+
p.pretty(value)
39+
p.text(",")
40+
p.breakable()
41+
p.text(")")
42+
43+
# pylint: disable=protected-access
44+
decorated_class._repr_pretty_ = repr_pretty # type: ignore[attr-defined]
45+
return decorated_class

src/qrules/combinatorics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
StateDefinition = Union[str, StateWithSpins]
3838

3939

40-
@implement_pretty_repr()
40+
@implement_pretty_repr
4141
@frozen
4242
class InitialFacts:
4343
edge_props: Dict[int, ParticleWithSpin] = field(factory=dict)

src/qrules/quantum_numbers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def _to_optional_int(optional_int: Optional[int]) -> Optional[int]:
164164
return int(optional_int)
165165

166166

167-
@implement_pretty_repr()
167+
@implement_pretty_repr
168168
@frozen(order=True)
169169
class InteractionProperties:
170170
"""Immutable data structure containing interaction properties.

src/qrules/solving.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
from .topology import Topology
5959

6060

61-
@implement_pretty_repr()
61+
@implement_pretty_repr
6262
@define
6363
class EdgeSettings:
6464
"""Solver settings for a specific edge of a graph."""
@@ -68,7 +68,7 @@ class EdgeSettings:
6868
qn_domains: Dict[Any, list] = field(factory=dict)
6969

7070

71-
@implement_pretty_repr()
71+
@implement_pretty_repr
7272
@define
7373
class NodeSettings:
7474
"""Container class for the interaction settings.
@@ -89,21 +89,21 @@ class NodeSettings:
8989
interaction_strength: float = 1.0
9090

9191

92-
@implement_pretty_repr()
92+
@implement_pretty_repr
9393
@define
9494
class GraphSettings:
9595
edge_settings: Dict[int, EdgeSettings] = field(factory=dict)
9696
node_settings: Dict[int, NodeSettings] = field(factory=dict)
9797

9898

99-
@implement_pretty_repr()
99+
@implement_pretty_repr
100100
@define
101101
class GraphElementProperties:
102102
edge_props: Dict[int, GraphEdgePropertyMap] = field(factory=dict)
103103
node_props: Dict[int, GraphNodePropertyMap] = field(factory=dict)
104104

105105

106-
@implement_pretty_repr()
106+
@implement_pretty_repr
107107
@frozen
108108
class QNProblemSet:
109109
"""Particle reaction problem set, defined as a graph like data structure.
@@ -123,7 +123,7 @@ class QNProblemSet:
123123
solving_settings: GraphSettings
124124

125125

126-
@implement_pretty_repr()
126+
@implement_pretty_repr
127127
@frozen
128128
class QuantumNumberSolution:
129129
node_quantum_numbers: Dict[int, GraphNodePropertyMap]
@@ -174,7 +174,7 @@ def get_name(rule: Any) -> str:
174174
return converted_dict
175175

176176

177-
@implement_pretty_repr()
177+
@implement_pretty_repr
178178
@define(on_setattr=attrs.setters.frozen)
179179
class QNResult:
180180
"""Defines a result to a problem set processed by the solving code."""

src/qrules/topology.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _to_frozenset(iterable: Iterable[int]) -> FrozenSet[int]:
168168
return frozenset(iterable)
169169

170170

171-
@implement_pretty_repr()
171+
@implement_pretty_repr
172172
@frozen(order=True)
173173
class Topology:
174174
"""Directed Feynman-like graph without edge or node properties.

src/qrules/transition.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ class SolvingMode(Enum):
103103
"""Find all possible solutions."""
104104

105105

106-
@implement_pretty_repr()
106+
@implement_pretty_repr
107107
@define(on_setattr=attrs.setters.frozen)
108108
class ExecutionInfo:
109109
not_executed_node_rules: Dict[int, Set[str]] = field(
@@ -180,7 +180,7 @@ def extend(
180180
)
181181

182182

183-
@implement_pretty_repr()
183+
@implement_pretty_repr
184184
@define
185185
class ProblemSet:
186186
"""Particle reaction problem set, defined as a graph like data structure.
@@ -736,14 +736,14 @@ def _strip_spin(state_definition: Sequence[StateDefinition]) -> List[str]:
736736
return particle_names
737737

738738

739-
@implement_pretty_repr()
739+
@implement_pretty_repr
740740
@frozen(order=True)
741741
class State:
742742
particle: Particle = field(validator=instance_of(Particle))
743743
spin_projection: float = field(converter=_to_float)
744744

745745

746-
@implement_pretty_repr()
746+
@implement_pretty_repr
747747
@frozen(order=True)
748748
class StateTransition:
749749
"""Frozen instance of a `.StateTransitionGraph` of a particle with spin."""

0 commit comments

Comments
 (0)