Last active
October 3, 2015 07:17
-
-
Save mjbommar/2414751 to your computer and use it in GitHub Desktop.
Introspective Python __repr__ like Java auto-gen toString() with dir() and eval()
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 __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