Skip to content

Commit

Permalink
easy_repr classs decorator
Browse files Browse the repository at this point in the history
adds a standardaized __repr__ method to cls
  • Loading branch information
phistakis authored and avivshahar committed Dec 8, 2020
1 parent 46a3056 commit 203d9bc
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
14 changes: 14 additions & 0 deletions easypy/humanize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -702,3 +703,16 @@ def __init__(self, value):

def __repr__(self):
return str(self.value)


def easy_repr(*attributes):
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 f'<{self.__class__.__name__}: {attrs}>'
cls.__repr__ = _nice_repr
return cls
return _decorator

39 changes: 38 additions & 1 deletion tests/test_humanize.py
Original file line number Diff line number Diff line change
@@ -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' \
Expand Down Expand Up @@ -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) == "<Class1: a: 'a', b: 'b', c: 1>"

# 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) == "<Class2: c: 1, a: 'a', d: 2>"

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'

0 comments on commit 203d9bc

Please sign in to comment.