Python Dir & Inspect: Get All Object Attributes & Methods
Discover how to use dir() Python and python inspect module like getmembers() to get all attributes, methods, and fields of any object. Alternatives to vars() python for lists, dicts, and built-ins without __dict__.
How to get all attributes, methods, and fields of any Python object? vars() doesn’t work for objects without __dict__, such as lists and dicts. What are the best alternatives using dir(), inspect, or other methods?
To inspect any Python object—whether it’s a list, dict, custom class, or built-in—and pull out all attributes, methods, and fields, turn to dir() for a fast list of names or the python inspect module’s getmembers() for detailed name-value pairs. Unlike vars() python, which bombs out on objects without __dict__ like lists (TypeError: vars() argument must have __dict__ attribute), dir python works everywhere by tapping into __dir__() under the hood. For finer control, inspect.getmembers python lets you filter methods from data fields effortlessly.
Contents
- Understanding Object Introspection: Dir Python vs Vars
- Why Vars() Fails on Lists, Dicts, and Built-ins
- Mastering Dir() Python for Quick Attribute Lists
- Python Inspect Module: Getmembers() for Full Details
- Filtering Methods vs Attributes with Inspect Predicates
- Handling Edge Cases: Classes, Slots, and Dynamic Attributes
- Best Practices and Workflows
- Sources
- Conclusion
Understanding Object Introspection: Dir Python vs Vars
Ever hit a wall trying to peek inside a Python object? Introspection lets you dynamically discover what’s there—attributes (data fields), methods, even inherited stuff. Dir python and vars() both help, but they’re worlds apart.
Dir() spits out a list of valid attributes and methods as strings. It’s universal, no exceptions. Run dir([1, 2, 3]) and you’ll see ['append', 'clear', ..., '__len__']—methods galore, even on lists. Why? It calls the object’s __dir__() if available, or builds a list from the namespace docs.python.org/3/library/functions.html#dir.
Vars()? That’s instance-only, pulling from __dict__. Great for your custom classes, but useless elsewhere. vars(my_instance) gives a dict of {attr: value}, yet vars({}) crashes. Simple as that docs.python.org/3/library/functions.html#vars. Need values too? Pair dir() with getattr(): loop through names and fetch getattr(obj, name).
Here’s the kicker: dir python catches class-level and inherited attributes that vars() misses entirely stackoverflow.com/questions/980249/difference-between-dir-and-vars-keys-in-python.
Why Vars() Fails on Lists, Dicts, and Built-ins
Picture this: you’re debugging, call vars(my_list), and boom—TypeError. Lists, dicts, tuples, even strings lack __dict__. They’re optimized C structures, not full-fledged class instances with dynamic namespaces.
my_list = [1, 2, 3]
print(vars(my_list)) # TypeError: vars() argument must have __dict__ attribute
Same for dicts: vars({}) fails. Built-ins like int or str? Nope. Vars() python shines only on objects with __dict__, like vars(object()) returns {} www.geeksforgeeks.org/python/difference-between-dir-and-vars-in-python/.
Frustrating, right? That’s why dir python or python inspect steps in—no __dict__ required.
Mastering Dir() Python for Quick Attribute Lists
Dir() python is your go-to for a no-fuss attribute dump. It lists everything accessible: methods, properties, even dunders.
# List example
print(dir([1, 2]))
# ['__add__', '__class__', ..., 'append', 'clear', 'copy', ...]
# Dict
print(dir({'a': 1}))
# ['__class__', ..., 'clear', 'copy', 'fromkeys', 'get', ...]
# Custom class
class Dog:
def bark(self):
pass
dog = Dog()
print(dir(dog)) # ['__class__', ..., 'bark']
Want just non-private, non-dunder stuff? Filter it:
import re
attrs = [attr for attr in dir(obj) if not re.match('^_[A-Z]|^__', attr)]
To get values, loop with getattr()—handles descriptors safely bobbyhadz.com/blog/python-get-attributes-of-object:
for name in dir(obj):
try:
value = getattr(obj, name)
print(f"{name}: {value}")
except AttributeError:
print(f"{name}: <unreadable>")
Pro tip: dir() on modules lists imports too. Versatile.
Python Inspect Module: Getmembers() for Full Details
When dir python gives names but you crave values, python inspect delivers. inspect.getmembers(obj) returns [(name, value)] pairs—methods and attributes docs.python.org/3/library/inspect.html.
import inspect
obj = [1, 2, 3]
members = inspect.getmembers(obj)
print(len(members)) # Dozens, way more than dir() alone
for name, value in members[:5]:
print(f"{name}: {type(value).__name__}")
# __add__: method, __class__: type, etc.
Unlike dir(), it resolves values, including callables. Perfect for python dir dict or lists. For static class attrs (no instance), use getmembers_static() (Python 3.11+) stackoverflow.com/questions/6886493/get-all-object-attributes-in-python.
Inspect python digs deeper than vars() ever could—no __dict__ needed.
Filtering Methods vs Attributes with Inspect Predicates
Raw lists overwhelm? Python inspect predicates slice precisely: methods, data fields, functions.
Key ones:
- Methods:
inspect.ismethodorinspect.isfunction - Data attrs:
lambda x: not inspect.isroutine(x) and not inspect.isfunction(x) - Custom classes only:
inspect.isclass
import inspect
def get_methods(obj):
return inspect.getmembers(obj, inspect.ismethod)
def get_attrs(obj):
return inspect.getmembers(obj,
lambda o: not inspect.isroutine(o) and
not inspect.isfunction(o) and
not inspect.isbuiltin(o))
print(get_methods([1,2])) # [('append', <built-in method...>), ...]
print(get_attrs([1,2])) # Mostly dunders like ('__class__', list)
For callable check: callable(value) works universally bobbyhadz.com/blog/python-get-attributes-of-object. Boom—methods vs fields separated.
Handling Edge Cases: Classes, Slots, and Dynamic Attributes
Classes with __slots__? Vars() skips them; dir() and inspect catch 'em.
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x, self.y = x, y
p = Point(1, 2)
print(dir(p)) # ['x', 'y'] + methods
print(inspect.getmembers(p)) # Full pairs
Dynamic attrs added post-init? Dir() adapts via __dir__(). VSCode or dynamic tools hiding stuff? Inspect.getmembers python uncovers more www.reddit.com/r/learnpython/comments/1dkialf/any_way_to_get_all_attributes_of_an_object_in/.
Modules: dir(sys) lists everything. Functions: inspect.getsource(func) for code too.
Best Practices and Workflows
Combine 'em: dir() for scouting, inspect.getmembers() for depth.
Ultimate inspector:
def inspect_object(obj):
print("Methods:", [name for name, _ in inspect.getmembers(obj, inspect.ismethod)])
print("Attributes:", [name for name, _ in inspect.getmembers(obj,
lambda x: not inspect.isroutine(x))])
print("Dir summary:", len(dir(obj)))
inspect_object({"key": "value"}) # Works flawlessly
Performance? Dir() fastest for lists; inspect for analysis. Avoid in hot loops—cache if needed www.pythonmorsels.com/inspecting-python-objects/.
Debugging? IPython’s %who or ??obj builds on this.
Sources
- Python dir() Documentation — Official guide to dir() for universal attribute listing: https://docs.python.org/3/library/functions.html#dir
- Python vars() Documentation — Explains vars() limitations on objects without dict: https://docs.python.org/3/library/functions.html#vars
- Python Inspect Module — Full details on getmembers() and predicates for introspection: https://docs.python.org/3/library/inspect.html
- Get All Object Attributes in Python — Stack Overflow solutions using dir() and getattr() loops: https://stackoverflow.com/questions/6886493/get-all-object-attributes-in-python
- Python Get Attributes of Object — Practical examples with inspect.getmembers() and filtering: https://bobbyhadz.com/blog/python-get-attributes-of-object
- Difference Between dir() and vars() — Comparison of scope and use cases: https://stackoverflow.com/questions/980249/difference-between-dir-and-vars-keys-in-python
- List Attributes of an Object — Filtering techniques for dir() output: https://stackoverflow.com/questions/2675028/list-attributes-of-an-object
- Inspecting Python Objects — Why inspect reveals more than dir() or vars(): https://www.pythonmorsels.com/inspecting-python-objects/
Conclusion
For any Python object, skip vars() headaches—dir python nails quick names, while python inspect with getmembers() unlocks full attributes, methods, and fields, even on lists or dicts. Filter smartly with predicates, handle slots and dynamics, and you’ll debug like a pro. Next time introspection stumps you, start with inspect.getmembers(obj)—it’s the powerhouse alternative.