Explore an unfamiliar value
Interactive debugging
Python · Function
dir() lists names in the current local scope or, when given an object, attempts to list its available attributes. It is primarily an interactive discovery aid and can be customized through __dir__().
dir() returns names available in the current local scope when called without an argument. Given an object, it attempts to produce a list of valid attribute names; if the object defines __dir__(), Python calls it to obtain that list.
dir(object, /)| Name | Type | Description |
|---|---|---|
object | object | Optional object whose available attribute names should be explored. If omitted, the current local scope is inspected. |
A list of names: local-scope names when called without an argument, or attempted valid attribute names for the supplied object.
dir() without an argument reports names currently available in the local scope.__dir__() method can supply the names returned by dir(object).__dir__() implementation is required to return an attribute list.__dir__() implementations can control what appears, so the output may differ from attributes discovered another way.value = 42
names = dir(value)
print("real", "real" in names)
print("count", len(names))Inspects an integer and checks whether the reported attribute names include real.
Interactive debugging
REPL work
Library inspection
dir() do with and without an argument?With no argument, dir() lists names in the current local scope. With an object, it attempts to list valid attributes for that object.
Follow-up: What can change the reported list? An object's __dir__() method is called when present, and the function's detailed behavior can vary across releases.
dir() a complete reflection of an object's attributes?The object form returns a list of names intended to be useful for interactive exploration. It is not guaranteed to represent every attribute rigorously or consistently.
Follow-up: Should production code use dir() to determine whether an API supports an operation? No; use an explicit interface or carefully handle the operation itself.
dir() reports?Yes. If the inspected object provides __dir__(), Python invokes it, and that method must return the attribute list.
Follow-up: What design concern follows? A custom implementation can expose a curated view, so callers should not assume the list is an authoritative inventory.
__dir__()getattr()hasattr()vars()