Python: dir() function

dir() function

The dir() function returns all properties and methods of the specified object, without the values. The function will return all the properties and methods, even built-in properties which are default for all object.

The function returns the list of names in the current local scope without arguments,. With an argument, attempt to return a list of valid attributes for that object.

Note: The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • The list contains the names of the module’s attributes if the object is a module object.
  • The list contains the names of its attributes, and recursively of the attributes of its bases if the object is a type or class object,
  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.


(Python 3)



The resulting list is sorted alphabetically.

Example: Python dir() function

<<< import struct
<<< dir()   # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
<<< dir(struct)   # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
<<< class Shape:
        def __dir__(self):
            return ['area', 'perimeter', 'location']
<<< s = Shape()
<<< dir(s)
['area', 'perimeter', 'location']

Example: Python dir() with integer

num = [4, 5, 6]

print('\nReturn Value from empty dir()')


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__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']

Return Value from empty dir()
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'num']

Example: dir() on User-defined Object

import struct
class Fruit:
        def __dir__(self):
            return ['Mango', 'Apple', 'Orange']
x = Fruit()


['Apple', 'Mango', 'Orange']

Python Code Editor:

Previous: dict()
Next: divmod()

Test your Python skills with w3resource's quiz

Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9