Python dir() Function
dir()It is a built-in function in Python used to obtain a list of object attributes and methods.
dir()Returns a list containing the names of all attributes and methods of the object. This function is very useful for exploring unknown objects, debugging code, and understanding class structures.
Word Definition: dirYesdirectoryAbbreviation of (directory), here referring to the list of attributes and methods.
Basic Syntax and Parameters
Syntax Format
dir(object) dir()
Parameter Description
- Parameter object(Optional):
- Type: Any object
- Description: The object whose attribute list you want to obtain. If no parameter is passed, it returns the list of names in the current scope.
Function Description
- Return Value: Returns a list of strings containing the names of attributes and methods.
- Features: The list is sorted alphabetically.
Examples
Example 1: View Object Attributes
Example
# View all attributes and methods of a list
print(dir([]))
# Output: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# View attributes of a string
print(dir(""))
# Output: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# View attributes of a dictionary
print(dir({}))
# Output: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(dir([]))
# Output: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# View attributes of a string
print(dir(""))
# Output: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# View attributes of a dictionary
print(dir({}))
# Output: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Expected Output:
Returns a list of all attribute and method names of the object.
Code Explanation:
- Starting with double underscore
__are special attributes/methods (magic methods). - Those without double underscores are public methods, such as
append,sortetc.
Example 2: View Custom Class Attributes
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# Create instance
p = Person("Tom", 20)
# View instance attributes
print(dir(p))
# Output: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# Filter to show only non-special methods
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # Output: ['age', 'greet', 'name']
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# Create instance
p = Person("Tom", 20)
# View instance attributes
print(dir(p))
# Output: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# Filter to show only non-special methods
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # Output: ['age', 'greet', 'name']
Expected Output:
['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name'] ['age', 'greet', 'name']
Code Explanation:
__dict__Contains the instance attributes of the object.- Filter
__out methods starting with (double underscores) to get public attributes.
Example 3: Using Without Parameters
Example
# Without parameters, returns the list of names in current scope
print(dir())
# Output: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# View after importing module
import os
print(dir())
# Will include 'os' in the list
# View module attributes
import json
print(dir(json))
# Output: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
print(dir())
# Output: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# View after importing module
import os
print(dir())
# Will include 'os' in the list
# View module attributes
import json
print(dir(json))
# Output: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
Expected Output:
Returns the list of names available in the current scope.
dir()It is a powerful tool for exploring Python objects and modules, especially suitable for interactive learning and debugging.
Other Extensions
Python3 Built-in Functions