Skip to content

Commit 3ec42ef

Browse files
committed
style: improve repr
1 parent ddc47f9 commit 3ec42ef

File tree

6 files changed

+71
-32
lines changed

6 files changed

+71
-32
lines changed

execution_engine/fhir/util.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ def get_coding(cc: CodeableConcept, system_uri: str | None = None) -> Coding:
1313
coding = [c for c in cc.coding if c.system == system_uri]
1414

1515
if cc.coding is None or len(coding) != 1:
16-
raise ValueError("CodeableConcept must have exactly one coding")
16+
raise ValueError(
17+
f"CodeableConcept must have exactly one coding, got {len(coding)}"
18+
)
1719

1820
return coding[0]
1921

execution_engine/omop/cohort/population_intervention_pair.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ def __repr__(self) -> str:
6363
"""
6464
return (
6565
f"{self.__class__.__name__}(\n"
66-
f" name={self._name},\n"
67-
f" url={self._url},\n"
66+
f" name={repr(self._name)},\n"
67+
f" url={repr(self._url)},\n"
6868
f" base_criterion={repr(self._base_criterion)},\n"
6969
f" population={self._population._repr_pretty(level=1).strip()},\n"
7070
f" intervention={self._intervention._repr_pretty(level=1).strip()}\n"

execution_engine/omop/cohort/recommendation.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,13 @@ def __repr__(self) -> str:
7575
return (
7676
f"{self.__class__.__name__}(\n"
7777
f" pi_pairs={pi_repr},\n"
78-
f" base_criterion={self._base_criterion},\n"
79-
f" name='{self._name}',\n"
80-
f" title='{self._title}',\n"
81-
f" url='{self._url}',\n"
82-
f" version='{self._version}',\n"
83-
f" description='{self._description}',\n"
84-
f" recommendation_id={self._id}\n"
85-
f" package_version='{self._package_version}',\n"
78+
f" base_criterion={repr(self._base_criterion)},\n"
79+
f" name={repr(self._name)},\n"
80+
f" title={repr(self._title)},\n"
81+
f" url={repr(self._url)},\n"
82+
f" version={repr(self._version)},\n"
83+
f" description={repr(self._description)},\n"
84+
f" package_version={repr(self._package_version)},\n"
8685
f")"
8786
)
8887

execution_engine/omop/criterion/combination/combination.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ def __repr__(self) -> str:
3838
Get the string representation of the operator.
3939
"""
4040
if self.operator in ["AT_LEAST", "AT_MOST", "EXACTLY"]:
41-
return f'{self.__class__.__name__}(operator="{self.operator}", threshold={self.threshold})'
41+
return f'{self.__class__.__qualname__}(operator="{self.operator}", threshold={self.threshold})'
4242
else:
43-
return f'{self.__class__.__name__}(operator="{self.operator}")'
43+
return f'{self.__class__.__qualname__}(operator="{self.operator}")'
4444

4545
def __eq__(self, other: object) -> bool:
4646
"""
@@ -207,6 +207,8 @@ def _build_repr(
207207
children: Sequence[tuple[str | None, Any]],
208208
params: list[tuple[str, Any]],
209209
level: int = 0,
210+
children_param_name: str = "criteria",
211+
children_is_sequence: bool = True,
210212
) -> str:
211213
"""
212214
Builds a multi-line string for this criterion combination,
@@ -265,11 +267,17 @@ def _build_repr(
265267
if method_defined:
266268
lines.extend(criteria_lines)
267269
lines.extend(kw_lines)
268-
else:
270+
elif children_is_sequence:
269271
lines.extend(kw_lines)
270-
lines.append(f"{child_indent}criteria=[")
272+
lines.append(f"{child_indent}{children_param_name}=[")
271273
lines.extend(criteria_lines)
272274
lines.append(f"{child_indent}],")
275+
else:
276+
assert len(criteria_lines) == 1
277+
lines.extend(kw_lines)
278+
lines.append(
279+
f"{child_indent}{children_param_name}={criteria_lines[0].strip()}"
280+
)
273281

274282
lines.append(f"{indent})")
275283

execution_engine/omop/criterion/combination/temporal.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,17 @@ def __init__(
7373

7474
super().__init__(operator=operator, criteria=criteria)
7575

76+
def _repr_pretty(self, level: int = 0) -> str:
77+
children = [(None, c) for c in self._criteria]
78+
79+
return self._build_repr(
80+
children,
81+
params=[],
82+
level=level,
83+
children_param_name="criterion",
84+
children_is_sequence=False,
85+
)
86+
7687

7788
class FixedWindowTemporalIndicatorCombination(TemporalIndicatorCombination):
7889
"""
@@ -138,7 +149,13 @@ def _repr_pretty(self, level: int = 0) -> str:
138149
("start_time", self.start_time),
139150
("end_time", self.end_time),
140151
]
141-
return self._build_repr(children, params, level)
152+
return self._build_repr(
153+
children,
154+
params=params,
155+
level=level,
156+
children_param_name="criterion",
157+
children_is_sequence=False,
158+
)
142159

143160
def dict(self) -> Dict:
144161
"""
@@ -377,7 +394,13 @@ def _repr_pretty(self, level: int = 0) -> str:
377394
params = [
378395
("interval_criterion", self.interval_criterion),
379396
]
380-
return self._build_repr(children, params, level)
397+
return self._build_repr(
398+
children,
399+
params=params,
400+
level=level,
401+
children_param_name="criterion",
402+
children_is_sequence=False,
403+
)
381404

382405
@property
383406
def interval_criterion(self) -> Criterion | CriterionCombination:

execution_engine/omop/criterion/meta.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __init__(self: object, *args: Any, **kwargs: Any) -> None:
7979
original_repr = namespace.get("__repr__")
8080

8181
if not original_repr:
82-
# Try to find an __init__ in the bases
82+
# Try to find an __repr__ in the bases
8383
for base in reversed(bases):
8484
if base.__repr__ is not object.__repr__:
8585
original_repr = base.__repr__
@@ -91,23 +91,30 @@ def __init__(self: object, *args: Any, **kwargs: Any) -> None:
9191
):
9292

9393
def __repr__(self: object) -> str:
94+
# Case 1: No real __init__ found at all => just return ClassName()
95+
if original_init is None:
96+
return f"{name}()"
97+
98+
# Case 2: If the class or its parents do define an __init__, we check
99+
# for _init_args. If the class isn't wrapping init, your class would
100+
# have to set _init_args itself (or you'll just get a normal object repr).
94101
if not hasattr(self, "_init_args"):
95102
return super(type(self), self).__repr__()
96-
sig = inspect.signature(original_init) if original_init else None
103+
104+
# Build param=value only if they differ from default
105+
sig = inspect.signature(original_init)
97106
parts = []
98-
if sig:
99-
for param_name, param in sig.parameters.items():
100-
if param_name == "self":
101-
continue
102-
default = param.default
103-
# Only show params if they differ from the default
104-
if (
105-
param_name in self._init_args
106-
and self._init_args[param_name] != default
107-
):
108-
parts.append(
109-
f"{param_name}={repr(self._init_args[param_name])}"
110-
)
107+
for param_name, param in sig.parameters.items():
108+
if param_name == "self":
109+
continue
110+
default = param.default
111+
if (
112+
param_name in self._init_args
113+
and self._init_args[param_name] != default
114+
):
115+
parts.append(
116+
f"{param_name}={repr(self._init_args[param_name])}"
117+
)
111118
return f"{name}({', '.join(parts)})"
112119

113120
# Tag it so children know it's auto-generated

0 commit comments

Comments
 (0)