dir()
Lists the names of the attributes and methods an object has, sorted alphabetically. With no argument, lists the names in the current scope.
dir()
dir(object)dir(something) answers the question "what can I do with this?". It returns a sorted list of names: the methods you can call and the attributes you can read. dir(str) shows every string method, from capitalize to zfill.
Called with no argument inside a function, dir() lists the local variable names that exist at that point.
The list includes many names that start and end with two underscores, such as __len__. These are special methods Python uses behind the scenes. Filter them out with if not name.startswith("_") to see the useful part. The exact list also grows with each Python version, so test for one name with in rather than counting them.
Parameters
| Parameter | What it is |
|---|---|
objectoptional | The object to look inside: a value, a class, a module. Leave it out to list the names in the current scope. |
Return value
A list of strings, sorted alphabetically.
Examples
1Check whether a type has a method
print("upper" in dir(str))
print("append" in dir(list))
print("append" in dir(tuple))True True False
Tuples cannot change, so they have no append.
2Find related methods by name
checks = [name for name in dir(str) if name.startswith("is")]
print(checks)['isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper']
3Look inside your own object
dir() shows the object's own attributes, the class attributes and the methods, all mixed and sorted.
class Account:
bank = "City Savings"
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
acc = Account("Leila", 250)
public = [name for name in dir(acc) if not name.startswith("_")]
print(public)['balance', 'bank', 'deposit', 'owner']
4What is in a module?
import math
print([name for name in dir(math) if name.startswith("log")])['log', 'log10', 'log1p', 'log2']
5Local names with dir()
def checkout(prices):
total = sum(prices)
count = len(prices)
print(dir())
checkout([4.5, 2.0])['count', 'prices', 'total']
Without an argument, dir() lists the names that exist right here: the parameter and the two local variables.
Common mistakes
Printing the whole list and getting lost
print(dir("text")) prints about 80 names, most of them __special__. Filter the list, or check for the one name you need with in.
Expecting dir() to show values
dir() gives names only. To see the values of your object's own attributes, use vars(obj), which returns a dictionary.
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
print(vars(Pet("Rex", 4))){'name': 'Rex', 'age': 4}Questions people ask
What is the difference between dir() and vars()?
dir() lists every name you can reach on an object, including methods and inherited ones. vars() returns the object's own attribute dictionary (__dict__), with values.
How do I list all methods of a class?
[n for n in dir(MyClass) if callable(getattr(MyClass, n)) and not n.startswith("_")] keeps only public callables. See callable() and getattr().
How do I check if an object has an attribute?
Use hasattr(): hasattr(obj, "name") is faster and clearer than "name" in dir(obj).