Skip to content

Instantly share code, notes, and snippets.

@mjbommar
Last active October 3, 2015 07:17
Show Gist options
  • Save mjbommar/2414751 to your computer and use it in GitHub Desktop.
Save mjbommar/2414751 to your computer and use it in GitHub Desktop.
Introspective Python __repr__ like Java auto-gen toString() with dir() and eval()
def __repr__(self):
'''
Return string representation.
'''
skipNone = True
reprString = type(self).__name__ + " ["
elements = dir(self)
for e in elements:
# Make sure we only display "public" fields; skip anything private (_*), that is a method/function, or that is a module.
if not e.startswith("_") and eval('type(self.{0}).__name__'.format(e)) not in ['DataFrame', 'function', 'method', 'builtin_function_or_method', 'module']:
value = eval("self." + e)
if value != None and skipNone == True:
reprString += "{0}={1}, ".format(e, value)
# Clean up trailing space and comma.
return reprString.strip(" ").strip(",") + "]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment