Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get some introspected info from objects. This is only prof-of-concept level code. Good for a one-off but needs work if you want it in production.
def obj_inspector(obj):
attributes = {}
functions = {}
special_functions = {}
for attribute_name in dir(obj):
attribute_value = getattr(obj, attribute_name)
attribute_category = attributes
if callable(attribute_value):
attribute_category = functions
if attribute_name.startswith('__') and attribute_name.endswith('__') and len(attribute_name) > 4:
attribute_category = special_functions
attribute_category[attribute_name] = attribute_value
container_values = []
# Gather information about contained things if this is a Collection object
if hasattr(obj, 'items'):
# Extract key, value pairs from Mapping type Collections. This is a little
# loosey-goosey since we have to alow for duck-typing
for key, value in obj.items():
container_values.append((key, value))
except Exception:
# Items doesn't return ke, value pairs so let's assume this obj has the items() method
# but isn't actually a Mapping
if not container_values:
for item in obj:
except AttributeError:
# Does not support iteration so it's not a Collection. It may be a Container but I
# don't think there's a generalizable way to tell how to extract items from a
# Container.
return (attributes, special_functions, functions, container_values)
if __name__ == '__main__':
from pprint import pprint
a = {1, 2, 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment