Python / dir() / Discover an Object’s Attribute Names
Python’s dir(object) returns a list of attribute names as strings. It does not return or execute the methods or attribute values themselves. The list is sorted by name, but objects can customize it, so it is not a guaranteed complete inventory of every accessible attribute.
The result contains names, not methods
Attributes are data or behavior associated with an object; methods are callable behavior associated with it. For a string, upper is a name and text.upper() is an actual call. The official dir() reference describes its focus on convenient interactive exploration.
These complete examples need only Python 3. Save the code as UTF-8 in dir_example.py and run python dir_example.py, or python3 in environments using that command. Each later example can replace the same file’s contents and run independently.
text = "hello"
names = dir(text)
print(type(names).__name__)
print(all(isinstance(name, str) for name in names))
print("upper" in names)
print(names == sorted(names))
print(text.upper())
Expected output:
list
True
True
True
HELLO
Every list element is a string. Discovering upper does not convert the text: the final line explicitly calls the method. Full attribute lists can vary across Python versions, so the example checks membership of a relevant name instead of reproducing a version-specific list.
Explore modules and lists in the same way
A module contains names for functions, constants, and other objects. After finding sqrt in dir(math), call it as math.sqrt(). Likewise, finding append does not change a list; calling it on the list does.
import math
print("sqrt" in dir(math))
print(math.sqrt(9))
items = []
print("append" in dir(items))
items.append("a")
print(items)
True
3.0
True
['a']
A name alone does not specify arguments or return values. Read help(math.sqrt) or the module’s official documentation. Leading underscores can indicate naming conventions, but do not enforce a security boundary preventing external access.
dir() and vars() answer different questions
dir(instance) may include names from its class and inheritance hierarchy as well as names stored on the instance. vars(object) instead returns the object’s __dict__. This is useful for directly stored instance attributes and values, but not every object has such a dictionary.
class User:
role = "reader"
def __init__(self, name):
self.name = name
def label(self):
return f"{self.role}:{self.name}"
user = User("Ada")
print([name for name in dir(user) if name in ("name", "role", "label")])
print(vars(user))
print(user.label())
['label', 'name', 'role']
{'name': 'Ada'}
reader:Ada
name is stored on the instance; role and label come from the class. That explains the different results. Here, vars(user) is the actual attribute dictionary, not a copy, so avoid modifying it while merely exploring. Calling vars() on an object without a dictionary, for example some classes using __slots__, can raise TypeError.
Omitting the argument examines the current namespace
dir() with no argument returns names in the current local namespace. It does not list all built-in functions or all installed packages. In a fresh, independent script, the explicitly defined marker appears, while the built-in abs is not directly listed.
marker = 7
print("marker" in dir())
print("abs" in dir())
True
False
An interactive shell or notebook may contain names from earlier execution, producing different results. Check the call’s location and any variables left from earlier work.
Understand custom __dir__() and dynamic attributes
An object can customize discovery through __dir__() and provide attributes dynamically through mechanisms such as __getattr__(). A missing name can therefore still be accessible, and a displayed name can fail on access.
class Dynamic:
def __getattr__(self, name):
if name == "answer":
return 42
raise AttributeError(name)
def __dir__(self):
return ["visible"]
item = Dynamic()
print(dir(item))
print("answer" in dir(item))
print(getattr(item, "answer"))
print(hasattr(item, "visible"))
['visible']
False
42
False
This object lists only visible but actually supplies answer. Use dir() for exploration or completion, then check documentation and the behavior you need. getattr() and hasattr() can execute attribute-lookup code, while dir() can invoke custom code too; none should automatically be assumed free of side effects.




