Created
February 4, 2015 08:34
-
-
Save japsu/34fc4dcccee3f299e718 to your computer and use it in GitHub Desktop.
__repr__ for classes that use __slots__
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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