The Python dir function provides a compilation of names present within the current local context. In cases where the object upon which this method is invoked possesses a method designated as dir, that specific method will be executed and is expected to return a collection of its attributes. It accepts a single argument of object type. Below is the function's signature.
Python dir Function Syntax
It has the following syntax:
dir ([object])
Parameters
- object: This function accepts an optional argument.
Return
It provides a collection of legitimate attributes associated with the object.
Different Examples for Python dir Function
Let’s explore a few examples of the dir function to grasp its capabilities.
Python dir Function Example 1
Let's develop a straightforward example to obtain a collection of valid attributes. This function accepts one parameter, which is not mandatory.
# Python dir() function example
# Calling function
att = dir()
# Displaying result
print(att)
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__']
Python dir Function Example 2
When we provide a parameter to this function, it yields attributes associated with the specified object. Below is an illustration.
# Python dir() function example
lang = ("C","C++","Python","Python")
# Calling function
att = dir(lang)
# Displaying result
print(att)
Output:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'count', 'index']
Python dir Function Example 3
Let’s explore an additional example to illustrate the usage of the dir function in Python.
# Python dir() function example
class Student():
def __init__(self,x):
return self.x
# Calling function
att = dir(Student)
# Displaying result
print(att)
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
Python dir Function Example 4
If the dir function has already been established within the object, the existing function will be invoked.
# Python dir() function example
class Student():
def __dir__(self):
return [10,20,30]
# Calling function
s = Student()
att = dir(s)
# Displaying result
print(att)
Output:
[10, 20, 30]