Python dir() Function
dir() is a built-in Python function that gets the list of an object's attributes and methods.
dir() It returns a list containing the names of all the object's attributes and methods. This function is very useful for exploring unknown objects, debugging code, and understanding class structures.
Word meaning: dir Is directoryis short for (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 is wanted. With no argument, 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.
- Feature: the list is sorted alphabetically.
Example
Example 1: viewing an object's attributes
Example
View all attributes and methods of a list
(
dir
(
[
]
)
)
Output: ['add', 'class', 'contains', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
View the attributes of a string
(
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 the attributes of a dictionary
(
dir
(
{
}
)
)
Output: ['class', 'contains', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Expected output:
Returns a list of all the object's attribute and method names.
Code analysis:
- Those starting with a double underscore
__are special attributes/methods (magic methods). - Those without a double underscore are public methods, such as
append,sort, etc.
Example 2: viewing a custom class's 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 an Instance
p
=
Person
(
"Tom"
,
20
)
View an instance's attributes
(
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
(
'_'
)
]
(
attrs
)
Output: ['age', 'greet', 'name']
Expected output:
['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
['age', 'greet', 'name']
Code analysis:
__dict__Includes the object's instance attributes.- Filtering
__-prefixed methods gives the public attributes.
Example 3: using it without arguments
Example
With no argument, returns the list of names in the current scope
(
dir
(
)
)
Output: ['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec']
View after importing a module
import
os
(
dir
(
)
)
'os' will be included in the list
View the module's attributes
import
json
(
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() is a powerful tool for exploring Python objects and modules, especially suited to interactive learning and debugging.
Python3 built-in function