Skip to content

Instantly share code, notes, and snippets.

@japsu
Created February 4, 2015 08:34
Show Gist options
  • Save japsu/34fc4dcccee3f299e718 to your computer and use it in GitHub Desktop.
Save japsu/34fc4dcccee3f299e718 to your computer and use it in GitHub Desktop.
__repr__ for classes that use __slots__
def slots_repr(self):
"""
Provides a readable, namedtuple-like __repr__ for classes that use __slots__.
Usage:
>>> class A(object):
... __slots__ = ['b']
... __repr__ = slots_repr
...
>>> a = A()
>>> a.b = 5
>>> repr(a)
"A(b=5)"
"""
return "{class_name}({formatted_slots})".format(
class_name=self.__class__.__name__,
formatted_slots=', '.join(
"{slot}={value}".format(
slot=slot,
value=repr(getattr(self, slot))
)
for slot in self.__class__.__slots__
if getattr(self, slot, None) is not None
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment