dir() Function in Python

Python dir() Function

The dir() function in Python is a built-in function that returns a list of valid attributes and methods for a given object. It can be used to examine the available members of an object, such as variables, methods, and classes.

Here is the general syntax of the dir() function:

dir(object)

The object parameter is optional. If provided, dir() returns the list of attributes and methods for that specific object. If object is not provided, dir() returns the list of attributes and methods in the current scope.

The dir() function is commonly used during development and debugging to explore the properties and capabilities of objects. It helps programmers understand what functionality is available and how to interact with the objects they are working with.

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

class Person:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        print(f"Hello, my name is {self.name}.")

person = Person("John")

# Using dir() without an object
print(dir())  # Lists the names in the current scope

# Using dir() with an object
print(dir(person))  # Lists the attributes and methods of the Person object

In the above example, dir() without an object returns the names in the current scope. dir(person) returns the attributes and methods of the Person object, including __init__() and greet().