Understanding dir() in Python

The dir() function is a built-in Python function used to list all attributes and methods available in an object, module, or class. It helps developers explore and debug Python objects.


๐Ÿ”น Syntax

dir(object)  # Returns a list of attributes and methods of the object
  • If no object is passed, dir() returns the list of all available names in the current scope.
  • If an object (module, class, function, etc.) is passed, it returns the list of available attributes and methods for that object.

๐Ÿ”น Example 1: Using dir() Without Arguments

print(dir())  # Lists all available names in the current scope

๐Ÿ”น Output (Example)

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

๐Ÿ”น Example 2: Using dir() With a Module

import math
print(dir(math))  # Lists all functions and attributes in the math module

๐Ÿ”น Output (Truncated)

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'asin', 'atan', 'ceil', 'cos', 'exp', 'factorial', 'floor', 'log', 'pi', 'sqrt']

๐ŸŽฏ This helps find available functions like sqrt(), log(), and pi.


๐Ÿ”น Example 3: Using dir() With an Object

class Sample:
    def method1(self):
        pass
    def method2(self):
        pass

obj = Sample()
print(dir(obj))  # Lists attributes and methods of the Sample class

๐Ÿ”น Output (Truncated)

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'method1', 'method2']

๐Ÿš€ The list includes special methods (__init__, __str__, etc.) and user-defined methods (method1(), method2()).


๐Ÿ”น Example 4: Filtering Attributes

If you only want to see user-defined attributes, you can filter out built-in methods:

attributes = [attr for attr in dir(obj) if not attr.startswith('__')]
print(attributes)  # Output: ['method1', 'method2']

๐Ÿ”น Example 5: Using dir() on Built-in Types

๐Ÿ“Œ dir() on a List

print(dir(list))

๐Ÿ”น Output (Truncated)

['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

๐ŸŽฏ This helps us find methods like .append(), .sort(), .pop(), etc.


๐Ÿ”น Summary

Use Case Example Purpose
Get current scope dir() Lists all variables in the current environment
Inspect module dir(math) Lists all functions & attributes of math
Inspect object dir(obj) Lists all methods & attributes of obj
Inspect list dir(list) Shows available list methods
Filter attributes [x for x in dir(obj) if not x.startswith('__')] Shows only user-defined attributes

๐ŸŽฏ Key Takeaways

โœ… dir() is useful for exploring Python objects.
โœ… It helps discover available methods and attributes in a module or class.
โœ… Filtering out __ methods gives user-defined attributes.

Do you need more real-world applications of dir()? ๐Ÿš€


Leave a Reply

Your email address will not be published. Required fields are marked *