Skip to content

Commit

Permalink
Fix __repr__ crashing when a member is uninitialized or deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
epsy committed Dec 6, 2017
1 parent defa6b6 commit 1e053f1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
20 changes: 20 additions & 0 deletions changelog.d/308.breaking.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The ``__repr__`` set by ``attrs``
no longer produces an ``AttributeError``
when the instance is missing some of the specified attributes
(either through deleting
or after using ``init=False`` on some attributes).

This can break code
that relied on ``repr(attr_cls_instance)`` raising ``AttributeError``
to check if any attr-specified members were unset.

If you were using this,
you can implement a custom method for checking this::

def has_unset_members(self):
for field in attr.fields(type(self)):
try:
getattr(self, field.name)
except AttributeError:
return True
return False
2 changes: 1 addition & 1 deletion src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@ def repr_(self):
return "{0}({1})".format(
class_name,
", ".join(
name + "=" + repr(getattr(self, name))
name + "=" + repr(getattr(self, name, NOTHING))
for name in attr_names
)
)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_dunders.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ class C(object):

assert "C(_x=42)" == repr(i)

def test_repr_uninitialized_member(self):
"""
repr signals unset attributes
"""
C = make_class("C", {
"a": attr.ib(init=False),
})

assert "C(a=NOTHING)" == repr(C())

@given(add_str=booleans(), slots=booleans())
def test_str(self, add_str, slots):
"""
Expand Down

0 comments on commit 1e053f1

Please sign in to comment.