Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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.

Version:

(Python 3)

Syntax:

dir([object])

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(dir(num))

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

Output:

['__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()
print(dir(x))

Output:

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

Python Code Editor:

Previous: dict()
Next: divmod()

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Find current directory and file's directory:

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")

Ref: https://bit.ly/3fy0R6m