Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

easy_repr classs decorator #11

Merged
merged 3 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 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,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

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'