Skip to content

Instantly share code, notes, and snippets.

@edudobay
Created March 22, 2017 20:46
Show Gist options
  • Save edudobay/1cdaf3451f0815d799ac8830f70a898c to your computer and use it in GitHub Desktop.
Save edudobay/1cdaf3451f0815d799ac8830f70a898c to your computer and use it in GitHub Desktop.
Simple "ToStringBuilder" for Python
def to_string_builder(obj, fields, filters={}):
return '<{name}({fields})>'.format(
name=type(obj).__name__,
fields=', '.join(
'{}={!r}'.format(name, value)
for name, value, predicate in
((name, getattr(obj, name), filters.get(name)) for name in fields)
if predicate is None or predicate(value)),
)
class Foo:
def __init__(self, a, b, c = None):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return to_string_builder(self, ('a', 'b', 'c'), {
'c': lambda c: c is not None,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment