Explain Codes LogoExplain Codes Logo

List attributes of an object

python
attribute-introspection
python-attributes
object-inspection
Alex KataevbyAlex Kataev·Nov 24, 2024
TLDR

To get an object's custom attributes excluding built-in ones, utilize vars() or filter the dir() results:

obj = YourClass() attributes = vars(obj) if hasattr(obj, '__dict__') else [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith('__')] print(attributes)

This way, you'll review only the relevant attributes of your object.

Diving deeper into attribute introspection

When handling complex Python objects, attributes can serve as insightful signposts. Let's unravel the mysteries of attribute introspection.

Function vs non-function attributes

Using callable(), we can differentiate between methods and non-function attributes:

methods = [attr for attr in dir(obj) if callable(getattr(obj, attr)) and not attr.startswith('__')] #Fishing for methods here. properties = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith('__')] # Nope, just properties.

Neat display with pprint

For an organized attribute overview, call upon the pprint module:

from pprint import pprint pprint(vars(obj)) # Prints in a "Can I speak to your manager?" style.

Inspecting with purpose

Step up your introspection game with Python's inspect module, perfect for a thorough object inquisition:

import inspect members = inspect.getmembers(obj, lambda a: not(inspect.isfunction(a))) # Inspector Gadget would be proud. print([attr for attr, value in members if not attr.startswith('_')])

Utilizing type() and inspect.isfunction()

Object attributes are like an assorted box of chocolates, you never know what you're gonna get. Use type() and inspect.isfunction() to sort them:

from inspect import isfunction attributes = {attr: getattr(obj, attr) for attr in dir(obj) if not isfunction(getattr(obj, attr))} # The chocolate sorter. for attr, value in attributes.items(): print(f"{attr}, type: {type(value)}") # Prints like a true chocolatier.

The vars() trick

The object's __dict__ property is equivalent to a secret compartment in your multi-tool. It stashes an object's modifiable attributes. Here, we unbox them using vars():

hidden_features = vars(obj) # Presto! New screwdriver!

The dir deal

An object with a custom __dir__ method is like a special edition Swiss Army Knife with its unique set of tools. We use the __dir__() function to list these attributes:

exclusive_tools = obj.__dir__() # Voila, a diamond file!

Filtering standard tools

To focus on the interesting and non-standard tools, we can filter out the common ones:

interesting_tools = [tool for tool in dir(obj) if not tool.startswith('_')] # Custom engraving? Yes please!