Created
March 22, 2017 20:46
-
-
Save edudobay/1cdaf3451f0815d799ac8830f70a898c to your computer and use it in GitHub Desktop.
Simple "ToStringBuilder" for Python
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 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