# Distributed under the terms of the Python license # see http://opensource.org/licenses/pythonpl.php for the full text. # stdlib from cStringIO import StringIO from itertools import ifilter from string import Template _repr_template = Template("<$class_name at $mem_loc$attrs>") def _object_attrs(_object, ignore_double_underscore, to_avoid_list, sort): attrs = dir(_object) if ignore_double_underscore: attrs = ifilter(lambda elem: not elem.startswith("__"), attrs) _to_avoid_list = getattr(_object, to_avoid_list, None) # Don't swallow exceptions if _to_avoid_list is not None: attrs = ifilter(lambda elem: not elem in _to_avoid_list, attrs) if sort: attrs = sorted(attrs) return attrs def make_repr(_object, ignore_double_underscore=True, to_avoid_list="repr_to_avoid", sort=True): """ Makes a nice string representation of an object, suitable for logging purposes. """ attrs = _object_attrs(_object, ignore_double_underscore, to_avoid_list, sort) buff = StringIO() for attr in attrs: attr_obj = getattr(_object, attr) if not callable(attr_obj): buff.write(" ") buff.write("%s=[%s]" % (attr, attr_obj)) out = _repr_template.safe_substitute(class_name=_object.__class__.__name__, mem_loc=hex(id(_object)), attrs=buff.getvalue()) buff.close() return out if __name__ == "__main__": class Foo(object): repr_to_avoid = ("x",) def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return make_repr(self) print Foo(1,2,3)