To inspect and print the structure or attributes of a Python object, you can use several methods depending on how deep you want the inspection to be. Here are some common approaches:
🔹 1. Using dir()
The built-in dir() function returns a list of names in the current local scope or a list of attributes of an object.
python
obj = SomeClass()
print(dir(obj))
This will show all attributes and methods (including inherited ones).
🔸 To filter out methods and show only data attributes, you can do something like:
python
attrs = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]
print(attrs)
🔹 2. Using vars()
The vars() function returns the __dict__ attribute of an object, which typically contains the object’s writable attributes.
python
print(vars(obj))
⚠️ Note: This only works if the object has a __dict__ attribute (i.e., it stores its attributes in a dictionary). It won't work for objects using __slots__, for example.
🔹 3. Using __dict__ directly
If you know the object has a __dict__, you can access it directly:
python
print(obj.__dict__)
🔹 4. Using pprint for Pretty Printing
If the attribute output is complex, pretty-print it:
python
from pprint import pprint
pprint(vars(obj))
🔹 5. Using inspect module (advanced inspection)
For more detailed introspection (e.g. class hierarchy, methods, signatures):
python
import inspect
print(inspect.getmembers(obj))
# Or to get methods only:
methods = inspect.getmembers(obj, predicate=inspect.ismethod)
🔹 6. Using help()
Although not structured data, help(obj) can give an overview of the object’s documentation and available methods.
python
help(obj)
🔸 Bonus: Custom Function to Print Attributes
Here’s a simple utility function:
python
def print_attributes(obj):
attrs = vars(obj)
for key, value in attrs.items():
print(f"{key}: {value}")
print_attributes(obj)
Or recursively:
python
def print_attributes_recursive(obj, indent=0):
for attr in dir(obj):
if not attr.startswith('__'):
try:
value = getattr(obj, attr)
print(" " * indent + f"{attr}: {value}")
if hasattr(value, '__dict__'):
print_attributes_recursive(value, indent + 4)
except Exception as e:
print(" " * indent + f"{attr}: <unreadable due to {e}>")
print_attributes_recursive(obj)
Let me know if you want to extract only certain types of attributes (like functions, classes, etc.)!