Skip to content

Instantly share code, notes, and snippets.

@iTrooz
Created June 23, 2023 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iTrooz/26680be6c8d43ca554e70b30f5ade02c to your computer and use it in GitHub Desktop.
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
"""
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