Created
June 23, 2023 17:24
-
-
Save iTrooz/26680be6c8d43ca554e70b30f5ade02c to your computer and use it in GitHub Desktop.
Auto generate __str__ for a python class, but with properties instead of attributes
This file contains 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
""" | |
With help from: | |
https://python-forum.io/thread-12462.html | |
https://stackoverflow.com/a/33800620 | |
""" | |
import inspect | |
def auto_str_props(cls): | |
properties = [] | |
for tp in inspect.getmro(cls): | |
for name, value in vars(tp).items(): | |
if isinstance(value, property): | |
properties.append(name) | |
def __str__(self): | |
return '%s(%s)' % ( | |
type(self).__name__, | |
', '.join('%s=%s' % (name, getattr(self, name)) for name in properties) | |
) | |
cls.__str__ = __str__ | |
return cls | |
# Usage: | |
@auto_str_props | |
class Test: | |
def __init__(self, foo, bar): | |
self._foo = foo | |
self._bar = bar | |
@property | |
def foo(self): | |
return self._foo | |
@property | |
def bar(self): | |
return self._bar | |
t = Test("abc", "def") | |
print(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment