Python dir()

Python dir() builtin function returns the list of names of attributes for a given object. If no object is given as argument, then dir() returns the list of names in the current local scope.

In this tutorial, we will learn about the syntax of Python dir() function, and learn how to use this function with the help of examples.

Syntax

The syntax of dir() function is

</>
Copy
dir([object])

where

ParameterRequired/OptionalDescription
objectOptionalA Python object.

Returns

The function returns an object of type list.

Examples

1. dir(object)

In this example, we will pass an object to the dir() function, and observe the list returned by it.

Python Program

</>
Copy
class X:
    a = 1
    b = 2

result = dir(X)

#print items in the result list
for item in result:
    print(item)

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__
a
b

2. No argument to dir()

In this example, we will not pass any object to the dir() function, and observe the list returned by it. Of course, we have two variables defined in the local scope.

Python Program

</>
Copy
x = 2
y = 4.4

result = dir()

#print items in the result list
for item in result:
    print(item)

Output

__annotations__
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
__spec__
x
y

Conclusion

In this Python Tutorial, we have learnt the syntax of Python dir() builtin function, and also learned how to use this function, with the help of Python example programs.