Python objects are the fundamental building blocks of the language. Which means everything in Python—integers, strings, functions, classes, and modules—is an object. Each object carries a set of attributes: data attributes (variables) and methods (functions). On the flip side, for developers debugging complex systems, building serialization tools, or writing introspective frameworks, the ability to python get all attributes of object instances dynamically is an essential skill. This capability allows you to inspect the internal state of an object at runtime without knowing its class definition beforehand, enabling powerful patterns like dynamic serialization, automated testing, and deep debugging.
Most guides skip this. Don't.
Understanding the Object Model: __dict__ and Beyond
Before diving into the specific functions, it is crucial to understand where attributes actually live. On top of that, in the standard CPython implementation, most user-defined objects store their instance attributes in a dictionary called __dict__. This mapping acts as the object's personal namespace.
When you write obj.In practice, __dict__['attr'] = value. attr = value, Python essentially executes obj.Think about it: accessing obj. attr triggers a lookup chain: first the instance __dict__, then the class __dict__, then parent classes (following the Method Resolution Order), and finally descriptors like properties or slots Practical, not theoretical..
That said, not all objects have a __dict__. Now, built-in types (like list, dict, str) and classes defining __slots__ without including '__dict__' store attributes in fixed-size internal structures (arrays or structs) for memory efficiency. This distinction dictates which inspection tool you should use.
The Built-in dir() Function: The First Line of Defense
The most common way to python get all attributes of object instances is the built-in dir() function. It is the "batteries included" approach, requiring no imports Small thing, real impact. Worth knowing..
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def greet(self):
return f"Hello, {self.name}"
user = User("Alice", "alice@example.com")
print(dir(user))
Output analysis:
The result is a sorted list of strings. Crucially, dir() does not just show instance variables (name, email). It aggregates:
- Instance attributes (found in
user.__dict__). - Class attributes and methods (
greet,__init__,__module__). - Inherited attributes (from
object:__str__,__eq__,__hash__, etc.). - Special methods (dunder methods) enabling protocol support.
Limitations of dir():
- It returns names, not values. You get a list of strings like
['email', 'greet', 'name']. To get values, you must iterate and callgetattr(). - It can be customized. A class can define a
__dir__()method to hide or fake attributes. - It misses "hidden" attributes. Attributes starting with double underscores (name mangling) appear with their mangled names (e.g.,
_User__secret), which can be confusing.
Deep Inspection with vars() and __dict__
If you need the actual values of instance attributes—effectively a snapshot of the object's state—vars() is the idiomatic choice. vars(obj) returns the __dict__ attribute of the object.
print(vars(user))
# Output: {'name': 'Alice', 'email': 'alice@example.com'}
This returns a mutable dictionary. Which means this is incredibly useful for:
- Serialization: Converting objects to JSON (
json. And dumps(vars(obj))). * Debugging: Pretty-printing state (pprint(vars(obj))). - Dynamic Updates: Bulk updating state (
obj.That said, __dict__. update(new_data)).
Critical Caveat: vars() raises a TypeError if the object does not have a __dict__ (e.g., built-ins, slotted classes without __dict__ slot).
# This fails
vars([1, 2, 3])
# TypeError: vars() argument must have __dict__ attribute
For slotted classes, you must inspect the slots manually (covered later).
The Power of inspect Module: Production-Grade Introspection
For strong tooling—like documentation generators, IDEs, or ORM libraries—the standard library inspect module provides a higher-level, safer API. It handles edge cases (built-ins, slots, properties) gracefully Not complicated — just consistent..
inspect.getmembers(object[, predicate])
This is the heavy lifter. It returns a list of (name, value) pairs sorted by name. It effectively combines dir() with getattr() Took long enough..
import inspect
members = inspect.getmembers(user)
for name, value in members:
print(f"{name}: {value} ({type(value).__name__})")
Filtering with Predicates:
The second argument, predicate, is a callable returning True for desired members. inspect provides ready-made predicates:
inspect.ismethod: Bound methods.inspect.isfunction: Functions (unbound).inspect.isroutine: Both methods and functions.inspect.isdatadescriptor/ismemberdescriptor: Properties, classmethods, staticmethods.inspect.isclass: Classes.
# Get only data attributes (non-callable, non-dunder)
data_attrs = inspect.getmembers(user, lambda a: not callable(a) and not a[0].startswith('__'))
print(data_attrs)
# [('email', 'alice@example.com'), ('name', 'Alice')]
inspect.getattr_static(object, name, default=...)
Standard getattr() triggers descriptors (properties, @classmethod, @staticmethod, data descriptors). Sometimes you want the raw attribute without executing the descriptor protocol (e.Even so, inspect. Practically speaking, , getting the property object itself, not its return value). Consider this: g. getattr_static retrieves the attribute from the class hierarchy without invoking it Most people skip this — try not to..
class Config:
@property
def debug_mode(self):
return True
cfg = Config()
print(getattr(cfg, 'debug_mode')) # True (executes property)
print(inspect.getattr_static(cfg, 'debug_mode')) # (raw descriptor)
Handling __slots__: The Memory-Efficient Edge Case
Classes defining __slots__ restrict the attributes an instance can have and typically remove __dict__ to save memory. Also, standard vars() fails here. To python get all attributes of object instances using slots, you must iterate the __slots__ definitions across the entire Method Resolution Order (MRO).
It sounds simple, but the gap is usually here Not complicated — just consistent..
class SlottedUser:
__slots__ = ('username', 'user_id', '__secret') # Note: name mangling applies here too
def __init__(self, username, user_id):
self.username = username
self.user_id = user_id
self.__secret = "hidden"
su = SlottedUser("bob", 42)
def get_slotted_attrs(obj):
attrs = {}
for cls in type(obj).Plus, startswith('__') and not slot. In practice, __mro__:
for slot in getattr(cls, '__slots__', []):
# Handle name mangling for private slots
if slot. endswith('__'):
mangled = f'_{cls.
print(get_slotted_attrs(su))
# {'username': 'b