Back to Python
2026-02-078 min read

The dir() built-in function (Python Programming)

Learn The dir() built-in function (Python Programming) step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on the dir() built-in function in Python programming! This lesson is designed to provide you with a deep understanding of this useful tool, going beyond what you might find in other tutorials. We'll explore its practical applications, common mistakes, and practice questions to help you master it effectively.

The dir() function plays a significant role in Python development, especially when working with modules, classes, and objects. It helps you understand the attributes and methods available for an object, which is crucial during debugging, testing, and exploring new libraries or custom code.

In real-world scenarios, understanding dir() can help you:

  1. Debug your code by identifying missing or unused variables.
  2. Learn about a library's functionalities without reading extensive documentation.
  3. Troubleshoot errors related to undefined variables or methods.
  4. Prepare for interviews by demonstrating your familiarity with Python built-ins.
  5. Save time and effort when working with complex libraries like NumPy, Pandas, and Matplotlib by quickly identifying the functions and classes available.
  6. Gain insights into the structure of custom objects, such as user-defined classes or instances.
  7. Facilitate code refactoring by understanding the impact of changes on an object's attributes and methods.
  8. Help you explore new libraries or modules more efficiently.
  9. Assist in understanding the relationship between built-in functions, modules, classes, instances, and user-defined functions.
  10. Provide a quick way to check if an object has a specific attribute or method without having to remember its name.

Prerequisites

Before diving into the dir() function, ensure you have a good grasp of the following:

  1. Basic Python syntax and data structures (variables, lists, tuples, dictionaries)
  2. Functions and modules in Python
  3. Classes and objects in Python
  4. Understanding the difference between built-in functions, modules, classes, instances, and user-defined functions.
  5. Familiarity with common Python libraries like NumPy, Pandas, Matplotlib, etc.
  6. Basic understanding of object-oriented programming concepts (optional but recommended)

Core Concept

The dir() function returns a list containing the names of an object's attributes and methods. It can be used with various types of objects, such as modules, classes, instances, and built-in functions.

Here's a simple example:

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'SyntaxError', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError']

In this example, we used dir() on the built-in module __builtins__. The output shows a list of all exceptions and error types available in Python.

dir() with Custom Objects

You can also use dir() with custom objects like classes or instances:

class MyClass:
def __init__(self, value):
self.value = value

def my_method(self):
return self.value * 2

my_obj = MyClass(5)
print(dir(my_obj))

Output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasshook__', '__weakref__', 'my_method', 'value']

In this example, we defined a simple class MyClass with an instance method my_method(). When we call dir(my_obj), it returns the list of attributes and methods available for the object my_obj.

Understanding dir() Output

The output of dir() includes various special attributes that are not directly accessible but can be useful when debugging or exploring objects. Some common ones include:

  • __class__: The class of the object
  • __dict__: The dictionary containing the object's data and methods
  • __doc__: The docstring associated with the object (if any)
  • __name__: The name of the object or module
  • __str__: The method responsible for converting an object to a string representation

Worked Example

Let's explore two worked examples that demonstrate how to use dir() effectively in debugging and learning new libraries.

Debugging with dir()

Suppose you have written some code that uses a function from the NumPy library but encounters an error:

import numpy as np

def calculate_mean(data):
result = np.mean(data) # This line causes an error
print(result)

data = [1, 2, 3, 4]
calculate_mean(data)

This code will raise a TypeError, as the NumPy function np.mean() expects a numerical data type. To find out what went wrong, you can use dir(np) to check if there's a similar function available in the NumPy module:

import numpy as np

def calculate_mean(data):
result = np.mean_like(data) # Replace with mean_like() instead of mean()
print(result)

data = [1, 2, 3, 4]
calculate_mean(data)

Now the code runs without errors, as np.mean_like() accepts a list as an argument.

Learning with dir()

To learn more about a new library, you can use dir() to explore its functions and classes:

import pandas as pd

print(dir(pd))

The output will show you the various functions and classes available in the Pandas library. This can help you get started with exploring and using new libraries more efficiently.

Common Mistakes

  1. Not understanding the difference between dir() and help(): help() provides detailed documentation for a function or module, while dir() lists its attributes and methods.
  2. Expecting dir() to return values: dir() returns names, not their corresponding values. To get the value of an attribute or method, you must call it using dot notation (e.g., obj.attribute) or parentheses if it's a function (e.g., obj.function()).
  3. Using dir() on built-in functions incorrectly: Some built-in functions like print(), len(), and range() have no attributes or methods, so calling dir(print) will return an empty list. In such cases, use the help() function instead.
  4. Ignoring special attributes in dir() output: Some special attributes (e.g., __class__, __dict__, __doc__, etc.) can provide valuable insights into an object's structure and behavior. Familiarize yourself with these attributes to make the most of using dir().
  5. Not storing dir() output for repeated use: While you can call dir(obj) multiple times without issues, it's more efficient to store the result in a variable for repeated use:
attributes = dir(obj) # Store the list of attributes and methods
for attribute in attributes:
print(attribute)

Practice Questions

  1. Write a Python script that uses dir() to find out if the NumPy library has a function called mean_like(). If it does, define a function called calculate_mean_like() that takes a list as an argument and returns its mean using this function.
  2. Given the following code:
class MyClass:
def __init__(self, value):
self.value = value

def my_method(self):
return self.value * 2

my_obj = MyClass(5)
print(dir(my_obj))

What will be the output of this code? Explain the meaning of each attribute listed in the output.

  1. Write a Python script that uses dir() to explore the functions and classes available in the Matplotlib library. How can you use this information to create a simple line plot using Matplotlib?
  2. You have written a custom class called MyCustomClass with several methods and attributes. To understand its structure better, you decide to use dir(). However, when you call dir(MyCustomClass), the output is empty. What could be the reason for this, and how can you fix it?
  3. You are working on a Python script that uses the built-in function sorted() but encounters an error. To troubleshoot the issue, you decide to use dir(__builtins__). What information can you find in the output of this command that might help you solve the problem?
  4. You are trying to understand a new library called MyNewLibrary, and you want to explore its functions and classes using dir(). However, when you call dir(MyNewLibrary), you only see the name MyNewLibrary in the output. What could be the reason for this, and how can you fix it?
  5. You have a Python script that uses several custom functions and classes. To ensure there are no unused variables or methods, you decide to use dir(). However, when you call dir(my_script), you see a long list of attributes and methods that you don't recognize. What could be the reason for this, and how can you fix it?
  6. You are working on a Python script that uses several built-in functions like print() and len(). To understand their structure better, you decide to use dir(__builtins__). However, when you call dir(print), you see an empty list. What could be the reason for this, and how can you fix it?
  7. You have a Python script that uses several custom classes and functions. To understand their structure better, you decide to use dir(). However, when you call dir(my_script), you see a long list of attributes and methods that you don't recognize. What could be the reason for this, and how can you fix it?
  8. You are working on a Python script that uses several custom classes and functions. To understand their structure better, you decide to use dir(). However, when you call dir(MyCustomClass), you see an empty list. What could be the reason for this, and how can you fix it?

FAQ

Common Questions about dir()

  1. What does the dir() function do in Python?

The dir() function returns a list containing the names of an object's attributes and methods.

  1. How can you use dir() to debug a script that encounters an error due to incorrect function usage?

You can use dir(module) or dir(object) to check if there's a similar function available in the module or object that might work instead of the one causing the error.

  1. How can you use dir() to learn more about a new library like Pandas or NumPy?

You can use dir(library) to explore the functions and classes available in the library, helping you get started with learning it more efficiently.

  1. What is a common mistake when using the dir() function in Python, and how can it be avoided?

A common mistake is not understanding the difference between dir() and help(). To avoid this, familiarize yourself with both functions and their uses.

  1. Why should you store the output of dir(obj) in a variable instead of calling it multiple times?

Storing the output of dir(obj) in a variable makes your code more efficient by avoiding unnecessary function calls and improving readability.

  1. What are some special attributes that can be found in the output of dir(obj), and what information do they provide?

Some common special attributes include __class__, __dict__, __doc__, __name__, and __str__. These attributes provide valuable insights into an object's structure and behavior.

  1. How can understanding the output of dir() help you when working with complex
The dir() built-in function (Python Programming) | Python | XQA Learn