Fix reprs.

This commit is contained in:
Tin Tvrtkovic 2016-03-16 22:28:43 +01:00
parent bef877320d
commit 1d21609c14
3 changed files with 24 additions and 7 deletions

View File

@ -210,7 +210,17 @@ def attributes(maybe_cl=None, these=None, repr_ns=None,
# It might not actually be in there, f.e. if using 'these'.
cl_dict.pop(ca_name, None)
cl_dict.pop('__dict__', None)
cl = type(cl.__name__, cl.__bases__, cl_dict)
if repr_ns is None:
qualname = getattr(cl, "__qualname__", None)
if qualname is not None:
class_name = qualname.rsplit(">.", 1)[-1]
else:
class_name = cl.__name__
else:
class_name = cl.__name__
cl = type(class_name, cl.__bases__, cl_dict)
return cl

View File

@ -246,26 +246,30 @@ class TestAttributes(object):
assert sentinel == getattr(C, method_name)
@pytest.mark.skipif(not PY3, reason="__qualname__ is PY3-only.")
def test_repr_qualname(self):
@pytest.mark.parametrize('slots_outer', [True, False])
@pytest.mark.parametrize('slots_inner', [True, False])
def test_repr_qualname(self, slots_outer, slots_inner):
"""
On Python 3, the name in repr is the __qualname__.
"""
@attributes
@attributes(slots=slots_outer)
class C(object):
@attributes
@attributes(slots=slots_inner)
class D(object):
pass
assert "C.D()" == repr(C.D())
assert "GC.D()" == repr(GC.D())
def test_repr_fake_qualname(self):
@pytest.mark.parametrize('slots_outer', [True, False])
@pytest.mark.parametrize('slots_inner', [True, False])
def test_repr_fake_qualname(self, slots_outer, slots_inner):
"""
Setting repr_ns overrides a potentially guessed namespace.
"""
@attributes
@attributes(slots=slots_outer)
class C(object):
@attributes(repr_ns="C")
@attributes(repr_ns="C", slots=slots_inner)
class D(object):
pass
assert "C.D()" == repr(C.D())

View File

@ -68,6 +68,9 @@ def test_slots_being_used():
assert non_slot_instance.method() == 1
assert slot_instance.method() == 1
assert attr.fields(C1Slots) == attr.fields(C1)
assert attr.asdict(slot_instance) == attr.asdict(non_slot_instance)
def test_basic_attr_funcs():
"""Test basic attr functionality on a simple slots class."""