Computer >> Computer tutorials >  >> Programming >> Python

dir() Method in Python


The dir() function returns list of the attributes and methods of any object like functions , modules, strings, lists, dictionaries etc. In this article we will see how to use the dir() in different ways in a program and for different requirements.

Only dir()

When we print the value of the dir() without importing any other module into the program, we get the list of methods and attributes that are available as part of the standard library that is available when a python program is initialized.

Example

Print(dir())

Output

Running the above code gives us the following result −

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

Additional modules

As we import additional modules and create variables, they get added to the current environment. Then those methods and attributes also become available in the print statement woth dir().

Example

import math

x = math.ceil(10.03)
print(dir())

Output

Running the above code gives us the following result −

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'x']

dir() for specific Modules

For specific modules we can find the methods and attributes contained in that module by passing it as parameter to the dir(). In the below example we see the methods available in the math module.

Example

import math

print(dir(math))

Output

Running the above code gives us the following result −

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', …., 'nan', … 'trunc']

dir() for a class

We can also apply the dir() to a class which was user created rather than in-bulit and gets its attributes listed through dir().

Example

class moviecount:

   def __dir__(self):
      return ['Red Man','Hello Boy','Happy Monday']

movie_dtls = moviecount()

print(dir(movie_dtls))

Output

Running the above code gives us the following result −

['Happy Monday', 'Hello Boy', 'Red Man']