dir(obj) is primarily an interactive exploration tool: it inspects obj's class and inherited classes and returns a sorted list of every attribute and method name it can find, including dunder methods like __init__ and __repr__. Called with no arguments inside a function or at the module level, it instead lists the names currently defined in that local or global scope.
1Understanding dir()
dir(obj) is primarily an interactive exploration tool: it inspects obj's class and inherited classes and returns a sorted list of every attribute and method name it can find, including dunder methods like __init__ and __repr__. Called with no arguments inside a function or at the module level, it instead lists the names currently defined in that local or global scope.
dir() is best used interactively in the REPL to explore what an unfamiliar object supports — for documentation and precise behavior, help(obj) or the official docs are more reliable than guessing from method names alone.
print(dir([]))2Practical Example
Here is a real-world application of dir() showing how it is used in production Python code.
class Car:
def drive(self): pass
def brake(self): pass
public_methods = [name for name in dir(Car) if not name.startswith("__")]
print(public_methods)3Best Practices
Follow these guidelines when working with dir():
1. Use dir(obj) at the REPL or in a debugger to discover available methods on unfamiliar objects
2. Filter out dunder methods with a list comprehension when you want to see just the 'public' API
3. Prefer hasattr(obj, 'method_name') over checking membership in dir(obj) when your code needs to make a runtime decision
Tip: dir() is best used interactively in the REPL to explore what an unfamiliar object supports — for documentation and precise behavior, help(obj) or the official docs are more reliable than guessing from method names alone.
print(dir([]))