Skip to content

Commit

Permalink
feat: implement Corgy.__str__ which calls __str__ on members
Browse files Browse the repository at this point in the history
  • Loading branch information
jayanthkoushik committed Dec 5, 2021
1 parent d1881f6 commit 7c1c003
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
10 changes: 8 additions & 2 deletions corgy/_corgy.py
Expand Up @@ -532,20 +532,26 @@ def __init__(self, **args):
grp_obj = grp_type(**grp_args)
setattr(self, grp_name, grp_obj)

def __repr__(self):
def _str(self, f_str: Callable[..., str]) -> str:
s = f"{self.__class__.__name__}("
for i, arg_name in enumerate(getattr(self.__class__, "__annotations__")):
if i != 0:
s = s + ", "
s = s + f"{arg_name}="
try:
_val_s = repr(getattr(self, arg_name))
_val_s = f_str(getattr(self, arg_name))
except AttributeError:
_val_s = "<unset>"
s = s + _val_s
s = s + ")"
return s

def __repr__(self) -> str:
return self._str(repr)

def __str__(self) -> str:
return self._str(str)

@classmethod
def parse_from_cmdline(
cls: type[_T], parser: Optional[argparse.ArgumentParser] = None, **parser_args
Expand Down
3 changes: 2 additions & 1 deletion tests/test_corgy.py
Expand Up @@ -150,12 +150,13 @@ class C(Corgy):
c.y = 1
self.assertEqual(c.y, 1)

def test_corgy_cls_has_correct_repr(self):
def test_corgy_cls_has_correct_repr_str(self):
c = self._CorgyCls()
c.x1 = [0, 1]
c.x2 = 2
c.x4 = "8"
self.assertEqual(repr(c), "_CorgyCls(x1=[0, 1], x2=2, x3=3, x4='8')")
self.assertEqual(str(c), "_CorgyCls(x1=[0, 1], x2=2, x3=3, x4=8)")

def test_corgy_cls_repr_handles_unset_values(self):
c = self._CorgyCls()
Expand Down

0 comments on commit 7c1c003

Please sign in to comment.