Python dir() function is used to list of valid attributes(properties, method and any attributes) for that object.
This function particularly helpful for inspections and debugging purposes, to explore the contents of objects and modules.
Syntax
dir(object)
Parameters
object: You can pass any object (modules, classes, instances, etc.) to this function.
Return value
If an object is provided, it returns a list of the object’s attributes, which includes its methods, along with any attributes it inherits from its base classes.
If no argument is given, it returns the list of names in the current local scope.
Example 1: Passing No Argument
# This will include built-in names and any names defined before this line.
print(dir())
# Defining a list named 'num_list' with some integer elements.
num_list = [1, 3, 5, 7]
# This time, it will include 'num_list' along with the previously listed names.
print(dir())
Output
Example 2: Passing Argument
# Defining a list named 'num_list' with some integer elements.
num_list = [1, 3, 5, 7]
# Printing the directory of 'num_list' to list its available attributes and methods.
print(dir(num_list))
Output
Example 3: Using with Modules
import math
print(dir(math))
Output
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign',
'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder',
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
Example 4: Using with Custom Objects
class MyClass:
def __dir__(self):
return ['custom_attribute1', 'custom_attribute2']
obj = MyClass()
print(dir(obj))
Output
['custom_attribute1', 'custom_attribute2']
The __dir__ method returns a list of attributes, and it can be overridden to customize the list of attributes that the dir() function returns for an instance of the class.
Example 5: Using with a Tuple
num_tuple= (21, 19, 18, 46)
print(dir(num_tuple))
Output
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']