Skip to content

Commit c8d41e6

Browse files
authored
__str__ to __repr__ (#3274)
* use self-documenting f-string in reprs * TestLibxcFunc add test_repr * use python behavior that __str__ falls back to __repr__ if not defined but not vice versa * improve ConversionElectrode.__repr__ and add test * fix test_energy_adjustment_repr
1 parent 538106b commit c8d41e6

File tree

16 files changed

+72
-139
lines changed

16 files changed

+72
-139
lines changed

pymatgen/apps/battery/conversion_battery.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,15 @@ def __hash__(self) -> int:
205205
return 7
206206

207207
def __repr__(self):
208+
cls_name, formula, n_steps = type(self).__name__, self.initial_comp.reduced_formula, self.num_steps
209+
avg_voltage, min_voltage, max_voltage = self.get_average_voltage(), self.min_voltage, self.max_voltage
208210
output = [
209-
f"Conversion electrode with formula {self.initial_comp.reduced_formula} and nsteps {self.num_steps}",
210-
f"Avg voltage {self.get_average_voltage()} V, min voltage {self.min_voltage} V, "
211-
f"max voltage {self.max_voltage} V",
212-
f"Capacity (grav.) {self.get_capacity_grav()} mAh/g, capacity (vol.) {self.get_capacity_vol()} Ah/l",
213-
f"Specific energy {self.get_specific_energy()} Wh/kg, energy density {self.get_energy_density()} Wh/l",
211+
f"{cls_name} with {formula=} and {n_steps=}, {avg_voltage=:.3f} V, "
212+
f"{min_voltage=:.3f} V, {max_voltage=:.3f} V",
213+
f"Capacity (grav.) {self.get_capacity_grav():.3f} mAh/g, capacity (vol.) "
214+
f"{self.get_capacity_vol():.3f} Ah/l",
215+
f"Specific energy {self.get_specific_energy():.3f} Wh/kg, energy density "
216+
f"{self.get_energy_density():.3f} Wh/l",
214217
]
215218
return "\n".join(output)
216219

pymatgen/core/libxcfunc.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -409,11 +409,12 @@ def __init__(self, _num):
409409
num: Number for the xc.
410410
"""
411411
info = _all_xcfuncs[self.value]
412-
self.kind = info["Kind"]
413-
self.family = info["Family"]
412+
self.kind = info["Kind"] # type: ignore
413+
self.family = info["Family"] # type: ignore
414414

415-
def __str__(self):
416-
return f"name={self.name}, kind={self.kind}, family={self.family}"
415+
def __repr__(self):
416+
name, kind, family = self.name, self.kind, self.family
417+
return f"{type(self).__name__}({name=}, {kind=}, {family=})"
417418

418419
@staticmethod
419420
def all_families():

pymatgen/core/periodic_table.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,7 +1161,8 @@ def __str__(self):
11611161
if self.oxi_state is not None:
11621162
output += f"{formula_double_format(abs(self.oxi_state))}{'+' if self.oxi_state >= 0 else '-'}"
11631163
if self._spin is not None:
1164-
output += f",spin={self._spin}"
1164+
spin = self._spin
1165+
output += f",{spin=}"
11651166
return output
11661167

11671168
def to_pretty_string(self) -> str:
@@ -1453,7 +1454,8 @@ def __str__(self):
14531454
if self.oxi_state is not None:
14541455
output += f"{formula_double_format(abs(self.oxi_state))}{'+' if self.oxi_state >= 0 else '-'}"
14551456
if self._spin is not None:
1456-
output += f",spin={self._spin}"
1457+
spin = self._spin
1458+
output += f",{spin=}"
14571459
return output
14581460

14591461

pymatgen/electronic_structure/cohp.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,6 @@ def __init__(self, efermi, energies, cohp, are_coops=False, are_cobis=False, ico
6161
self.icohp = icohp
6262

6363
def __repr__(self):
64-
return str(self)
65-
66-
def __str__(self):
6764
"""Returns a string that can be easily plotted (e.g. using gnuplot)."""
6865
if self.are_coops:
6966
cohpstring = "COOP"

pymatgen/entries/computed_entries.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,12 @@ def explain(self):
9090
"""Return an explanation of how the energy adjustment is calculated."""
9191

9292
def __repr__(self):
93-
name, value, uncertainty = self.name, float(self.value), self.uncertainty
93+
name, value, uncertainty, description = self.name, float(self.value), self.uncertainty, self.description
9494
# self.cls might not be a dict if monty decoding is enabled in the new MPRester
9595
# which hydrates all dicts with @class and @module keys into classes in which case
9696
# we expect a Compatibility subclass
9797
generated_by = self.cls.get("@class", "unknown") if isinstance(self.cls, dict) else type(self.cls).__name__
98-
return (
99-
f"{type(self).__name__}({name=}, {value=:.3}, {uncertainty=:.3}, "
100-
f"description={self.description}, {generated_by=})"
101-
)
98+
return f"{type(self).__name__}({name=}, {value=:.3}, {uncertainty=:.3}, {description=}, {generated_by=})"
10299

103100

104101
class ConstantEnergyAdjustment(EnergyAdjustment):

pymatgen/io/abinit/abitimer.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -650,11 +650,9 @@ def __init__(self, sections, info, cpu_time, wall_time):
650650
self.mpi_rank = info["mpi_rank"].strip()
651651
self.fname = info["fname"].strip()
652652

653-
def __str__(self):
654-
return (
655-
f"file={self.fname}, wall_time={self.wall_time:.1f}, "
656-
f"mpi_nprocs={self.mpi_nprocs}, omp_nthreads={self.omp_nthreads}"
657-
)
653+
def __repr__(self):
654+
file, wall_time, mpi_nprocs, omp_nthreads = self.fname, self.wall_time, self.mpi_nprocs, self.omp_nthreads
655+
return f"{type(self).__name__}({file=}, {wall_time=:.3}, {mpi_nprocs=}, {omp_nthreads=})"
658656

659657
@property
660658
def ncpus(self):

pymatgen/io/vasp/inputs.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1493,9 +1493,6 @@ def write_file(self, filename):
14931493
f.write(str(self))
14941494

14951495
def __repr__(self):
1496-
return str(self)
1497-
1498-
def __str__(self):
14991496
lines = [self.comment, str(self.num_kpts), self.style.name]
15001497
style = self.style.name.lower()[0]
15011498
if style == "l":

pymatgen/io/wannier90.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,8 @@ def write_file(self, filename: str) -> None:
155155
f.write_record(self.data[ib].flatten("F"))
156156

157157
def __repr__(self) -> str:
158-
return (
159-
f"<UNK ik={self.ik} nbnd={self.nbnd} ncl={self.is_noncollinear}"
160-
f" ngx={self.ng[0]} ngy={self.ng[1]} ngz={self.ng[2]}>"
161-
)
158+
ik, nbnd, ncl, ngx, ngy, ngz = self.ik, self.nbnd, self.is_noncollinear, *self.ng
159+
return f"{(type(self).__name__)}({ik=}, {nbnd=}, {ncl=}, {ngx=}, {ngy=}, {ngz=})"
162160

163161
def __eq__(self, other: object) -> bool:
164162
if not isinstance(other, Unk):

pymatgen/symmetry/analyzer.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -247,9 +247,10 @@ def _get_symmetry(self):
247247
"""
248248
d = spglib.get_symmetry(self._cell, symprec=self._symprec, angle_tolerance=self._angle_tol)
249249
if d is None:
250+
symprec = self._symprec
250251
raise ValueError(
251252
f"Symmetry detection failed for structure with formula {self._structure.formula}. "
252-
f"Try setting symprec={self._symprec} to a different value."
253+
f"Try setting {symprec=} to a different value."
253254
)
254255
# Sometimes spglib returns small translation vectors, e.g.
255256
# [1e-4, 2e-4, 1e-4]
@@ -1686,8 +1687,5 @@ def __init__(self, sch_symbol, operations, tol: float = 0.1):
16861687
self.sch_symbol = sch_symbol
16871688
super().__init__(generate_full_symmops(operations, tol))
16881689

1689-
def __str__(self):
1690-
return self.sch_symbol
1691-
16921690
def __repr__(self):
1693-
return str(self)
1691+
return self.sch_symbol

pymatgen/transformations/advanced_transformations.py

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,8 @@ def apply_transformation(self, structure: Structure):
8181
trans = SubstitutionTransformation({self.charge_balance_sp: {self.charge_balance_sp: 1 - removal_fraction}})
8282
return trans.apply_transformation(structure)
8383

84-
def __str__(self):
85-
return f"Charge Balance Transformation : Species to remove = {self.charge_balance_sp}"
86-
8784
def __repr__(self):
88-
return str(self)
85+
return f"Charge Balance Transformation : Species to remove = {self.charge_balance_sp}"
8986

9087
@property
9188
def inverse(self):
@@ -142,11 +139,8 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool |
142139
structures.append({"transformation": t, "structure": t.apply_transformation(structure)})
143140
return structures
144141

145-
def __str__(self):
146-
return f"Super Transformation : Transformations = {' '.join(map(str, self._transformations))}"
147-
148142
def __repr__(self):
149-
return str(self)
143+
return f"Super Transformation : Transformations = {' '.join(map(str, self._transformations))}"
150144

151145
@property
152146
def inverse(self):
@@ -246,11 +240,8 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool |
246240
outputs.append({"structure": new_structure})
247241
return outputs
248242

249-
def __str__(self):
250-
return f"Multiple Substitution Transformation : Substitution on {self.sp_to_replace}"
251-
252243
def __repr__(self):
253-
return str(self)
244+
return f"Multiple Substitution Transformation : Substitution on {self.sp_to_replace}"
254245

255246
@property
256247
def inverse(self):
@@ -489,11 +480,8 @@ def sort_func(s):
489480
return self._all_structures[0:num_to_return]
490481
return self._all_structures[0]["structure"]
491482

492-
def __str__(self):
493-
return "EnumerateStructureTransformation"
494-
495483
def __repr__(self):
496-
return str(self)
484+
return "EnumerateStructureTransformation"
497485

498486
@property
499487
def inverse(self):
@@ -557,11 +545,8 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool |
557545
outputs.append(output)
558546
return outputs
559547

560-
def __str__(self):
561-
return "SubstitutionPredictorTransformation"
562-
563548
def __repr__(self):
564-
return str(self)
549+
return "SubstitutionPredictorTransformation"
565550

566551
@property
567552
def inverse(self):
@@ -2199,11 +2184,8 @@ def apply_transformation(self, structure: Structure) -> Structure:
21992184
coords_are_cartesian=True,
22002185
)
22012186

2202-
def __str__(self):
2203-
return f"{__name__} : rattle_std = {self.rattle_std}"
2204-
22052187
def __repr__(self):
2206-
return str(self)
2188+
return f"{__name__} : rattle_std = {self.rattle_std}"
22072189

22082190
@property
22092191
def inverse(self):

0 commit comments

Comments
 (0)