dir() overview
The dir() function in Python returns a list of valid attributes of the given object. dir() can be used on data structures like lists, tuples, sets and dictionaries or user-defined objects like classes. This is useful to find attributes and methods of an object.
dir() on data structures
To return all valid attributes of a data structure use the dir() function.
# check attributes of data structures
myList = [1, 2, 3]
print(dir(myList))
The dir() function returns a list of all attributes.
['__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']
We can for example see that it's possible to call the following methods:
.append()
.clear()
.copy()
.extend()
.count()
.index()
.insert()
.pop()
.remove()
.reverse()
.sort()
on the list.
dir() on user-defined object
The dir() function is also useful to find the attributes of a user-defined object like a class.
# using dir() to find attributes of a class
class Person:
age = 25
name = 'mike'
mike = Person()
print(dir(mike))
In this example mike has the attributes age and name.
['__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__', 'age', 'name']
dir() syntax
The syntax of dir() is:
dir(object)
dir() arguments
The dir() function accepts only one object at a time. If more than one argument is passed, a TypeError exception is raised.
dir() return values
The dir() function returns a list of all valid attributes.
If no object is passed, dir() returns a list of all variables in the current local scope.
['Person', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'length', 'mike', 'my', 'myDictionary', 'myList', 'myString', 'myTuple']
related functions
Some related functions are:
the hasattr() function to check if an object has an specific attribute
the delattr() function to delete a specific attribute
the getattr() function to receive the value of a specific attribute