The dir()
function is an inbuilt Python function that returns a list of names (mostly, attributes) associated with an object. The object can range from modules, classes, and instances to basic Python data types like lists, tuples, and strings. It helps developers in introspection, debugging, and interactive exploration.
Syntax:
The primary syntax of the dir()
function is quite straightforward:
dir([object])
Parameters:
object (optional): The object whose attributes you want to fetch. If the object is not provided, dir()
returns the list of names in the current local scope.
For a simple instance, consider the exploration of attributes and methods available for a list:
print(dir([]))
This might output a list containing methods like append
, clear
, copy
, and more. These are all the attributes associated with a list object in Python.
Return Value:
The dir( ) function returns the list of attributes of the object
Examples:
Python dir() with a List
Using the dir()
function with a list involves passing a list object as an argument to dir()
. This will return a list of all the methods and attributes associated with lists.
# dir() with empty list
print(dir([]))
Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Interpretation of the Output:
When you execute the above code, you’ll see an output comprising several methods. Here’s a breakdown of some of the commonly used methods you’d find:
append: This method appends an element to the end of the list.
lst = [1, 2, 3]
lst.append(4)
print(lst) # Output: [1, 2, 3, 4]
clear: It removes all items from the list.
lst = [1, 2, 3]
lst.clear()
print(lst) # Output: []
copy: Returns a shallow copy of the list.
lst = [1, 2, 3]
new_lst = lst.copy()
print(new_lst) # Output: [1, 2, 3]
extend: Extends the list by appending all the items from an iterable.
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
lst1.extend(lst2)
print(lst1) # Output: [1, 2, 3, 4, 5, 6]
index: Returns the first index at which a value occurs.
lst = ['apple', 'banana', 'cherry']
print(lst.index('banana')) # Output: 1
insert: Inserts an item at a given position.
lst = [1, 3, 4]
lst.insert(1, 2) # Inserting 2 at index 1
print(lst) # Output: [1, 2, 3, 4]
pop: Removes the item at the specified position, or the last item if no index is specified.
lst = [1, 2, 3, 4]
lst.pop(2)
print(lst) # Output: [1, 2, 4]
remove: Removes the first occurrence of a value.
lst = [1, 2, 3, 2]
lst.remove(2)
print(lst) # Output: [1, 3, 2]
reverse: Reverses the elements of the list in place.
lst = [1, 2, 3, 4]
lst.reverse()
print(lst) # Output: [4, 3, 2, 1]
sort: Sorts the list in place.
lst = [3, 1, 4, 2]
lst.sort()
print(lst) # Output: [1, 2, 3, 4]
Special Attributes:
In addition to these methods, the output will include several attributes with double underscores (often referred to as “dunder” methods). Examples include __len__
, __getitem__
, __setitem__
, etc. These are special methods that Python internally uses to emulate container behaviors. For instance:
__len__
corresponds to the built-in len()
function.
lst = [1, 2, 3]
print(len(lst)) # Internally, this calls lst.__len__()
The dir()
function, when used with a list, provides a comprehensive overview of the list’s methods and attributes. This can serve as a quick reference for developers, aiding in effective utilization of lists and their associated operations.
dir() with a Set
To examine the methods and attributes available to a set, simply pass a set object to the dir()
function:
print(dir(set()))
Output:
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
dir() with a Tuple
To observe the methods and attributes associated with tuples, pass a tuple object to the dir()
function:
print(dir(()))
Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
dir() with a User-defined Object
The dir()
function is particularly interesting when applied to user-defined objects because it provides a glimpse into the attributes, methods, and internal mechanisms that Python associates with a custom class and its instances.
Let’s start by creating a simple class:
class MyClass:
class_attribute = "I'm a class attribute!"
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute
def my_method(self):
return "This is a method!"
Now, if you create an instance of this class and use dir()
:
obj = MyClass("I'm an instance attribute!")
print(dir(obj))
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'class_attribute', 'instance_attribute', 'my_method']
Interpretation of the Output:
Executing the above code will present a list containing both the standard attributes/methods Python associates with all objects, and the custom attributes/methods we defined. Here’s a breakdown:
- User-defined Attributes/Methods:
class_attribute
: This is a class-level attribute we’ve defined.instance_attribute
: This attribute is initialized in the constructor.my_method
: A method we’ve defined for our class.
- Built-in Attributes/Methods:
__class__
: The class to which an instance belongs.__delattr__
,__getattribute__
,__setattr__
: Methods to manipulate object attributes.__dict__
: A dictionary containing the object’s namespace.__doc__
: Class documentation string, if provided.__init__
: The constructor method.__module__
: The module in which the class was defined.__repr__
,__str__
: Methods to represent the object as a string.- … and many more.
It’s worth noting that many of the methods with double underscores (referred to as “dunder” methods) are special methods in Python. They are hooks for built-in behaviors and operations. For example, if you define the __str__
method, it determines the behavior when you use the str()
function or print()
function on an instance of your class.
Exploring More:
If you modify the class to include special methods, or inherit from another class, the output of dir()
will reflect these changes:
class ParentClass:
def parent_method(self):
return "This is from the parent class!"
class MyClass(ParentClass):
# ... same as before ...
obj = MyClass("Attribute value")
print(dir(obj))
Now, in the output of dir(obj)
, you’ll see parent_method
in addition to the other methods and attributes. This is because MyClass
inherits from ParentClass
.
dir( ) with Modules:
When you invoke dir()
on a module, it returns the names of all the functions, classes, and variables defined in that 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', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
This will display a list of all functions and attributes available in the math
module, like sin
, cos
, pi
, and so on.
Conclusion
The dir()
function stands as a testament to Python’s introspective capabilities, allowing developers to dive deep into the anatomy of objects, modules, and classes. Whether you’re debugging, exploring new libraries, or documenting APIs, dir()
serves as an invaluable tool in your Python toolkit.