From 0044c0b7805dcec359a1aac4f5db13d5534cea32 Mon Sep 17 00:00:00 2001 From: Jacob Lifshay Date: Mon, 15 Aug 2022 23:07:40 -0700 Subject: [PATCH] add support for plain_data __repr__ with fields that aren't set --- src/nmutil/plain_data.py | 12 +++++++++++- src/nmutil/test/test_plain_data.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/nmutil/plain_data.py b/src/nmutil/plain_data.py index 1c170a4..ace4d61 100644 --- a/src/nmutil/plain_data.py +++ b/src/nmutil/plain_data.py @@ -5,6 +5,16 @@ class FrozenPlainDataError(AttributeError): pass +class __NotSet: + """ helper for __repr__ for when fields aren't set """ + + def __repr__(self): + return "" + + +__NOT_SET = __NotSet() + + def _decorator(cls, *, eq, unsafe_hash, order, repr_, frozen): if not isinstance(cls, type): raise TypeError( @@ -175,7 +185,7 @@ def _decorator(cls, *, eq, unsafe_hash, order, repr_, frozen): def __repr__(self): parts = [] for name in fields: - parts.append(f"{name}={getattr(self, name)!r}") + parts.append(f"{name}={getattr(self, name, __NOT_SET)!r}") return f"{self.__class__.__qualname__}({', '.join(parts)})" add_method_or_error(__repr__) diff --git a/src/nmutil/test/test_plain_data.py b/src/nmutil/test/test_plain_data.py index 6952fe1..a087e6e 100644 --- a/src/nmutil/test/test_plain_data.py +++ b/src/nmutil/test/test_plain_data.py @@ -58,6 +58,15 @@ class PlainDataF2(PlainDataF1): self.z = z +@plain_data() +class UnsetField: + __slots__ = "a", "b" + + def __init__(self, **kwargs): + for name, value in kwargs.items(): + setattr(self, name, value) + + class TestPlainData(unittest.TestCase): def test_fields(self): self.assertEqual(fields(PlainData0), ()) @@ -182,6 +191,11 @@ class TestPlainData(unittest.TestCase): "PlainData2(a=1, b=2, x='x', y='y', z=3)") self.assertEqual(repr(PlainDataF2(1, 2, x="x", y="y", z=3)), "PlainDataF2(a=1, b=2, x='x', y='y', z=3)") + self.assertEqual(repr(UnsetField()), + "UnsetField(a=, b=)") + self.assertEqual(repr(UnsetField(a=2)), "UnsetField(a=2, b=)") + self.assertEqual(repr(UnsetField(b=3)), "UnsetField(a=, b=3)") + self.assertEqual(repr(UnsetField(a=5, b=3)), "UnsetField(a=5, b=3)") def test_frozen(self): not_frozen = PlainData0() -- 2.30.2