diff --git a/easypy/humanize.py b/easypy/humanize.py index b5f8189..c7ea279 100644 --- a/easypy/humanize.py +++ b/easypy/humanize.py @@ -10,6 +10,7 @@ from math import ceil from collections import namedtuple from contextlib import contextmanager +from inspect import getargspec from io import StringIO from datetime import datetime, timedelta @@ -702,3 +703,20 @@ def __init__(self, value): def __repr__(self): return str(self.value) + + +def easy_repr(*attributes): + """ + Create a simple __repr__ function for the decorated class. + """ + + def _decorator(cls): + assert attributes, 'must provide at least one attribute' + + def _nice_repr(self): + attrs = ', '.join('{}={!r}'.format(attr, getattr(self, attr)) for attr in attributes) + return '<{self.__class__.__name__}: {attrs}>'.format(self=self, attrs=attrs) + cls.__repr__ = _nice_repr + return cls + return _decorator + diff --git a/tests/test_humanize.py b/tests/test_humanize.py index a7d694d..ee1ce48 100644 --- a/tests/test_humanize.py +++ b/tests/test_humanize.py @@ -1,4 +1,4 @@ -from easypy.humanize import from_hexdump, hexdump, IndentableTextBuffer, format_table +from easypy.humanize import from_hexdump, hexdump, IndentableTextBuffer, format_table, easy_repr _SAMPLE_DATA = b'J\x9c\xe8Z!\xc2\xe6\x8b\xa0\x01\xcb\xc3.x]\x11\x9bsC\x1c\xb2\xcd\xb3\x9eM\xf7\x13`\xc8\xce\xf8g1H&\xe2\x9b' \ @@ -88,3 +88,40 @@ def test_format_table_without_titles(): "{'x': 'x'}|b'bytes'|string\n") assert output == format_table(table, titles=False) + + +def test_easy_repr(): + @easy_repr('a', 'b', 'c') + class Class1: + def __init__(self, a, b, c, d): + self.a = a + self.b = b + self.c = c + self.d = d + a = Class1('a', 'b', 1, 2) + assert repr(a) == "" + + # change order + @easy_repr('c', 'a', 'd') + class Class2: + def __init__(self, a, b, c, d): + self.a = a + self.b = b + self.c = c + self.d = d + a = Class2('a', 'b', 1, 2) + assert repr(a) == "" + + try: + @easy_repr() + class Class3: + def __init__(self, a, b, c, d): + self.a = a + self.b = b + self.c = c + self.d = d + except AssertionError: + pass + else: + assert False, 'easy_repr with no attributes should not be allowed' +