Published on

The Python `dir()` Function

Table of Contents

the dir() Function

In Python, the dir() function is a built-in function that returns a list of names in the current local scope or the names of an object's attributes. Here's the general syntax:


If object is not provided, dir() returns the names in the current local scope. If an object is passed as an argument, dir() returns the names of the object's attributes and methods.

Here's an example of using the dir() function:

# Example 1: Names in current local scope

# Example 2: Names of an object's attributes
my_list = [1, 2, 3]

In the first example, dir() is called without any arguments, so it returns the names in the current local scope. It will include the names of variables, functions, classes, and other objects defined in the current scope.

In the second example, dir(my_list) returns the names of attributes and methods of the my_list object. These may include methods like append(), remove(), or attributes like count, index, and so on, that are available for list objects.

Note that dir() returns a list of strings, and it may include some built-in names or names defined by imported modules, depending on the context in which it is called.