When I build a small reporting script, I often receive an unfamiliar object from a library, API response, or custom class. I need to know what that object contains before I can use it safely. Rather than guessing method names or digging through code first, I use the Python dir() function.
The dir() function gives you a quick list of names available on an object. Those names may include methods, attributes, built-in features, and values you created yourself. It is one of the most useful inspection tools for debugging, learning a new module, and exploring Python objects interactively.
This practical Python tutorial shows how to use the Python dir() function with variables, lists, strings, modules, custom classes, and real debugging examples.
What Is the Python dir() Function?
The dir() function is a built-in Python function that returns a list of names available in the current scope or on a specific object.
In simple terms, it answers this question:
“What can I access or use with this Python object?”
The returned list usually includes:
- Attributes: Values stored on an object, such as
name,price, orstatus - Methods: Functions attached to an object, such as
append(),upper(), orreplace() - Special methods: Python’s internal methods, such as
__init__,__str__, and__len__ - Inherited members: Features received from a parent class
The basic syntax is:
dir([object])
The square brackets mean the object is optional.
- Use
dir()without an argument to inspect the current Python scope. - Use
dir(object)to inspect a specific object.
The function works in Python 3, including Python 3.10, 3.11, 3.12, and newer versions.
Python dir() Function Syntax
Here is the basic form:
dir()
Or:
dir(object_name)
The object_name can be almost anything in Python:
- A string
- A list
- A dictionary
- A module
- A function
- A class
- An instance of a class
- A built-in data type
For example, if you are working with a list of sales amounts, you can inspect its available methods before writing your processing logic.
monthly_sales = [1200, 1450, 980, 1750]
print(dir(monthly_sales))
Sample output:
['__add__', '__class__', '__class_getitem__', '__contains__',
'__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
You can refer to the screenshot below to see the output.
The output differs slightly across Python versions. However, common list methods such as append, remove, sort, and pop remain available.
If you want to learn those list methods in depth, see this guide on how to add elements to an empty Python list and this tutorial to sort a list in Python without using the sort function.
Use Python dir() Without an Argument
When you call dir() without an argument, Python returns names available in your current scope.
A scope is the area of your program where a variable, function, or class name exists. For example, variables created at the top of a script belong to the global scope.
Here is a simple example.
employee_name = "Emily Johnson"
department = "Finance"
monthly_target = 25000
print(dir())
Sample output:
['__annotations__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__',
'department', 'employee_name', 'monthly_target']
You can refer to the screenshot below to see the output.
Python includes several special names that begin and end with double underscores. These are often called dunder names, short for “double underscore” names.
The important part of the output is your own variables:
'department'
'employee_name'
'monthly_target'
This approach helps when you are working in the Python shell, Jupyter Notebook, or an IDE console and want to confirm which variables are available.
Filter Your Own Names From dir()
The default output includes Python’s internal names. You can filter them out and show only names that do not begin with an underscore.
employee_name = "Emily Johnson"
department = "Finance"
monthly_target = 25000
available_names = [name for name in dir() if not name.startswith("_")]
print(available_names)
Sample output:
['department', 'employee_name', 'monthly_target']
This uses a list comprehension, which is a compact way to create a new list from another sequence. The condition removes names that start with _.
This pattern is useful in automation scripts where you need to inspect variables during development. If you are new to list processing, you may also find this guide helpful on how to filter lists in Python.
Use the Python dir() Function With Strings
Strings include many built-in methods for cleaning, formatting, splitting, and checking text. I use dir() on strings when I remember that Python has a feature but cannot remember its exact name.
For example, imagine a customer-support report that contains employee names in inconsistent letter cases.
customer_name = "michael brown"
string_methods = [name for name in dir(customer_name) if not name.startswith("_")]
print(string_methods)
Sample output:
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Now you can spot useful methods such as title(), strip(), and replace().
Here is a practical example that uses those methods.
customer_name = " michael brown "
clean_name = customer_name.strip().title()
print(clean_name)
Sample output:
Michael Brown
The strip() method removes extra spaces from the beginning and end. The title() method changes the first letter of each word to uppercase.
For more practical string work, see how to remove spaces from a string in Python and convert a string to lowercase in Python.
Use Python dir() With Lists
Lists are common in reporting scripts, data-cleaning tasks, and file-processing automation. The Python dir() function helps you discover the available operations without memorizing every list method.
Here is an example with a weekly order list.
weekly_orders = ["Laptop", "Monitor", "Keyboard", "Mouse"]
list_methods = [name for name in dir(weekly_orders) if not name.startswith("_")]
print(list_methods)
Sample output:
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
You can refer to the screenshot below to see the output.
Suppose you notice the append and sort methods in the output. You can use them to update your list.
weekly_orders = ["Laptop", "Monitor", "Keyboard", "Mouse"]
weekly_orders.append("Webcam")
weekly_orders.sort()
print(weekly_orders)
Sample output:
['Keyboard', 'Laptop', 'Monitor', 'Mouse', 'Webcam']
You can use the same inspection approach before working with a list from a CSV file, a database query, or an API response.
Pro Tip: I have found that
dir()saves time when I switch between data types. A method that works on a list, such asappend(), does not work on a string. Checkingdir()first helps me avoid avoidableAttributeErrormessages.
Use Python dir() With Dictionaries
A dictionary stores data as key-value pairs. It works well for employee records, product details, JSON data, and application settings.
For example, a reporting script may store a sales representative’s details in a dictionary.
sales_rep = {
"name": "Daniel Carter",
"region": "Texas",
"monthly_sales": 18450
}
dictionary_methods = [name for name in dir(sales_rep) if not name.startswith("_")]
print(dictionary_methods)
Sample output:
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values']
The output tells you that dictionaries support methods such as get(), items(), keys(), and update().
Here is how you can use get() safely.
sales_rep = {
"name": "Daniel Carter",
"region": "Texas",
"monthly_sales": 18450
}
sales_target = sales_rep.get("monthly_target", 20000)
print(sales_target)
Sample output:
20000
The get() method returns the value for a key. If the key does not exist, it returns the default value you provide instead of causing an error.
You can explore dictionaries further by learning how to check whether a key exists in a Python dictionary or update dictionary values in Python.
Use Python dir() With Modules
A module is a Python file or built-in package that contains reusable code. Modules help you organize functions, classes, and constants.
For example, the built-in math module includes functions for calculations. You can inspect it with dir().
import math
math_items = [name for name in dir(math) if not name.startswith("_")]
print(math_items)
Sample output:
['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'exp',
'factorial', 'floor', 'fmod', 'fsum', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'lcm', 'ldexp', 'lgamma', 'log', 'log10',
'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod',
'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau',
'trunc', 'ulp']
Now you know that the module contains ceil, floor, sqrt, and factorial.
Here is a simple reporting example that rounds an average order value up to the next whole dollar.
import math
average_order_value = 124.25
rounded_value = math.ceil(average_order_value)
print(rounded_value)
Sample output:
125
If you need more details about numeric helpers, explore the ceil function in Python and the floor function in Python.
Use Python dir() With Custom Classes
A class is a blueprint for creating objects. An object stores related data and behavior in one place.
In real projects, I often use dir() to inspect objects from custom classes. This is especially useful when a teammate creates a class, when a library returns an object, or when you revisit code after several months.
Here is a complete example for a local sales-reporting tool.
class SalesReport:
report_type = "Monthly Sales"
def __init__(self, representative, amount):
self.representative = representative
self.amount = amount
def format_summary(self):
return f"{self.representative} generated ${self.amount:,} in sales."
def meets_target(self, target):
return self.amount >= target
report = SalesReport("Olivia Davis", 28450)
class_items = [name for name in dir(report) if not name.startswith("_")]
print(class_items)
Sample output:
['amount', 'format_summary', 'meets_target', 'report_type', 'representative']
The output includes:
amountandrepresentative, which are instance attributes created inside__init__report_type, which is a class attributeformat_summaryandmeets_target, which are methods
Now use the discovered methods and attributes.
class SalesReport:
report_type = "Monthly Sales"
def __init__(self, representative, amount):
self.representative = representative
self.amount = amount
def format_summary(self):
return f"{self.representative} generated ${self.amount:,} in sales."
def meets_target(self, target):
return self.amount >= target
report = SalesReport("Olivia Davis", 28450)
print(report.format_summary())
print(report.meets_target(25000))
Sample output:
Olivia Davis generated $28,450 in sales.
True
This is a practical use case for dir() because it lets you inspect the object before calling a method. You can learn more about object-oriented code through this guide on building a simple OOP project in Python and this explanation of the difference between class and instance variables.
Python dir() Function for Debugging
The Python dir() function becomes especially valuable when an error says an object does not have an attribute.
For example, suppose you expect order_details to be a dictionary. You try to use keys(), but Python raises an error.
order_details = ["Order-101", "Laptop", 1299]
print(order_details.keys())
Sample output:
AttributeError: 'list' object has no attribute 'keys'
The error tells you that order_details is a list, not a dictionary. Run dir() to confirm the available options.
order_details = ["Order-101", "Laptop", 1299]
available_methods = [name for name in dir(order_details) if not name.startswith("_")]
print(available_methods)
Sample output:
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
The output does not include keys(), which confirms the problem.
You can then fix the data structure.
order_details = {
"order_id": "Order-101",
"product": "Laptop",
"amount": 1299
}
print(order_details.keys())
Sample output:
dict_keys(['order_id', 'product', 'amount'])
This simple troubleshooting approach helps you quickly separate a data-type issue from a coding mistake. For related debugging help, read how to fix the module object has no attribute error in Django and learn about Python exception handling with multiple exceptions.
Python dir() vs vars()
Both dir() and vars() inspect objects, but they answer different questions.
| Feature | Python dir() function | Python vars() function |
|---|---|---|
| Main purpose | Lists available names on an object | Returns an object’s attribute dictionary |
| Includes inherited names | Usually yes | Usually no |
| Includes methods | Yes | Usually no, unless stored directly |
| Best use case | Discovering available methods and attributes | Inspecting attributes stored directly on an object |
| Works with all objects | Generally yes | Only objects with a __dict__ attribute |
Here is an example.
class Employee:
company = "Brightline Solutions"
def __init__(self, name, role):
self.name = name
self.role = role
def introduce(self):
return f"{self.name} works as a {self.role}."
employee = Employee("Sophia Miller", "Data Analyst")
print(vars(employee))
print([name for name in dir(employee) if not name.startswith("_")])
Sample output:
{'name': 'Sophia Miller', 'role': 'Data Analyst'}
['company', 'introduce', 'name', 'role']
vars(employee) shows only instance attributes stored on that employee object. dir(employee) gives a broader view, including the class attribute company and the introduce() method.
For a detailed comparison, read Python dir() vs vars() difference.
Things to Keep in Mind
- Expect special names: The
dir()output includes many double-underscore names such as__init__and__str__. These special methods support Python’s internal object behavior. - Do not treat dir() as complete documentation:
dir()gives you names, not full explanations or method arguments. Usehelp(object)or your editor’s documentation panel when you need parameter details. - Filter output for readability: Use
[name for name in dir(object) if not name.startswith("_")]when you want to focus on practical public attributes and methods. - Check the object type first: Combine
dir()withtype()when debugging. A list, dictionary, string, and custom object expose different methods. - Do not use dir() for security checks:
dir()exposes names that code can access, but it does not prove that an attribute is safe, public, or appropriate to modify. - Use it during development, not as core production logic:
dir()works well for exploration, debugging, and admin tools. Normal application code should call known methods directly.
Frequently Asked Questions
What does dir() do in Python?
The dir() function returns a list of names available on an object or in the current scope. These names can include methods, attributes, special methods, and inherited members. Developers mainly use it to explore unfamiliar objects and debug code.
What is the difference between dir() and help() in Python?
dir() lists the available names on an object. help() provides documentation about an object, function, class, or module. Use dir() to discover a name, then use help() to understand how to use it.
Does Python dir() return methods only?
No. The Python dir() function returns both methods and attributes. For a custom object, it can show data such as name and amount, along with methods such as save() or calculate_total().
Why does dir() show names with double underscores?
Names such as __init__, __str__, and __len__ are Python special methods. Python uses them to support object creation, printing, length checks, comparisons, and other built-in behavior. Most beginners can ignore them until they start working with classes and object-oriented programming.
Can I use dir() on a module in Python?
Yes. You can pass an imported module to dir(). For example, dir(math) shows functions and constants available in the math module, such as sqrt, ceil, pi, and factorial.
Can dir() help fix AttributeError in Python?
Yes. When Python raises an AttributeError, use dir(object) to see what attributes and methods the object actually supports. This often reveals that you used the wrong data type or misspelled a method name.
The Python dir() function gives you a fast way to inspect variables, built-in types, modules, classes, and custom objects. Start by using it in the Python shell or while debugging a small automation script, then use the names you discover to write clearer and more reliable code.
You May Also Like
- Built-in functions in Python
- How to define a function in Python
- Python constructor examples
- Python method resolution order explained
- Dynamic attribute creation with setattr and getattr
Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.