Skip to content

Commit 027c593

Browse files
authored
Merge pull request #11 from phistakis/patch-1
easy_repr classs decorator
2 parents 46a3056 + 39e3468 commit 027c593

2 files changed

Lines changed: 56 additions & 1 deletion

File tree

easypy/humanize.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from math import ceil
1111
from collections import namedtuple
1212
from contextlib import contextmanager
13+
from inspect import getargspec
1314
from io import StringIO
1415
from datetime import datetime, timedelta
1516

@@ -702,3 +703,20 @@ def __init__(self, value):
702703

703704
def __repr__(self):
704705
return str(self.value)
706+
707+
708+
def easy_repr(*attributes):
709+
"""
710+
Create a simple __repr__ function for the decorated class.
711+
"""
712+
713+
def _decorator(cls):
714+
assert attributes, 'must provide at least one attribute'
715+
716+
def _nice_repr(self):
717+
attrs = ', '.join('{}={!r}'.format(attr, getattr(self, attr)) for attr in attributes)
718+
return '<{self.__class__.__name__}: {attrs}>'.format(self=self, attrs=attrs)
719+
cls.__repr__ = _nice_repr
720+
return cls
721+
return _decorator
722+

tests/test_humanize.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from easypy.humanize import from_hexdump, hexdump, IndentableTextBuffer, format_table
1+
from easypy.humanize import from_hexdump, hexdump, IndentableTextBuffer, format_table, easy_repr
22

33

44
_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():
8888
"{'x': 'x'}|b'bytes'|string\n")
8989

9090
assert output == format_table(table, titles=False)
91+
92+
93+
def test_easy_repr():
94+
@easy_repr('a', 'b', 'c')
95+
class Class1:
96+
def __init__(self, a, b, c, d):
97+
self.a = a
98+
self.b = b
99+
self.c = c
100+
self.d = d
101+
a = Class1('a', 'b', 1, 2)
102+
assert repr(a) == "<Class1: a='a', b='b', c=1>"
103+
104+
# change order
105+
@easy_repr('c', 'a', 'd')
106+
class Class2:
107+
def __init__(self, a, b, c, d):
108+
self.a = a
109+
self.b = b
110+
self.c = c
111+
self.d = d
112+
a = Class2('a', 'b', 1, 2)
113+
assert repr(a) == "<Class2: c=1, a='a', d=2>"
114+
115+
try:
116+
@easy_repr()
117+
class Class3:
118+
def __init__(self, a, b, c, d):
119+
self.a = a
120+
self.b = b
121+
self.c = c
122+
self.d = d
123+
except AssertionError:
124+
pass
125+
else:
126+
assert False, 'easy_repr with no attributes should not be allowed'
127+

0 commit comments

Comments
 (0)