Introduction
The dir() method tries to return a list of valid attributes of the object, without the values. the dir() function is a built-in function that lists the identifiers defined in the module. These modules may include functions, classes, and variables.
Syntax
The syntax of dir() function is
dir([object])
Examples
print(dir())
// Output: ['__annotations__', '__builtins__', '__doc__', '__loader__',
'__name__', '__package__', '__spec__']
If a module name is defined in the dir() function, it will return the list of modules in that module ๐
def print_var(x):
print(x)
x=18
print_var(x)
print(dir(print_var))
// Output: 18
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__get__', '__getattribute__', '__globals__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__',
'__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__',
'__qualname__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']
If no name is specified, the dir() will return the list of modules defined in the current module ๐
list1 = []
a= 10;
print(dir())
// Output: ['__annotations__', '__builtins__', '__doc__', '__loader__',
'__name__', '__package__', '__spec__', 'a', 'list1']
It shows the functions belonging to math module ๐
import math
print(dir(math))
//Output: ['__doc__', '__loader__', '__name__', '__package__', '__spec__',
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb',
'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt',
'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm',
'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan',
'tanh', 'tau', 'trunc']
Uses of dir() function
- It is usually used for debugging purposes in simple day-to-day programs. The dir() function can list out all the attributes of that parameter passed,
- dir() function is really useful when handling a lot of classes and functions, separately.
- The dir() function can also list out all the available attributes for the module/list/dictionary. So it helps to know the new modules faster.
ย