Skip to content

Commit cf62b15

Browse files
committed
refactor(SubprocessCommand): Skip defaults in __repr__ of dataclass
In dataclass, skip printing of attributes that are defaults. Credit to Pietro Oldrati - https://stackoverflow.com/a/72161437/1396928 - License is unilicense: - https://stats.stackexchange.com/users/357193/user2246849 - https://unlicense.org/
1 parent c849487 commit cf62b15

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

libvcs/utils/subprocess.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import dataclasses
3535
import subprocess
3636
import sys
37+
from operator import attrgetter
3738
from typing import (
3839
IO,
3940
Any,
@@ -343,6 +344,22 @@ def run(
343344
check=check,
344345
)
345346

347+
def __repr__(self):
348+
"""Skip defaults.
349+
350+
Credit: Pietro Oldrati, 2022-05-08, Unlicense
351+
352+
See also: https://stackoverflow.com/a/72161437/1396928
353+
"""
354+
nodef_f_vals = (
355+
(f.name, attrgetter(f.name)(self))
356+
for f in dataclasses.fields(self)
357+
if attrgetter(f.name)(self) != f.default
358+
)
359+
360+
nodef_f_repr = ",".join(f"{name}={value}" for name, value in nodef_f_vals)
361+
return f"{self.__class__.__name__}({nodef_f_repr})"
362+
346363

347364
#
348365
# Composable mixins

0 commit comments

Comments
 (0)