Skip to content

python dir

In Python, the dir() function returns a list of all the attributes and methods of an object. This includes built-in attributes and methods, as well as any attributes and methods that have been defined by the user.

The dir() function can be used with any object, including:

  • Variables
  • Functions
  • Modules
  • Classes
  • Instances of classes

For example, the following code will print a list of all the attributes and methods of the print() function:

Python

print(dir(print))

Output:

[‘class‘, ‘delattr‘, ‘dict‘, ‘doc‘, ‘format‘, ‘getattribute‘, ‘hash‘, ‘init‘, ‘module‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘_end’, ‘_file’, ‘_line’, ‘_mode’, ‘_name’, ‘_newlines’, ‘_output_encoding’, ‘_printoptions’, ‘_string_buffer’, ‘_unicode’, ‘end’, ‘file’, ‘flush’, ‘format’, ‘help’, ‘newlines’, ‘output_encoding’, ‘precision’, ‘rjust’, ‘sep’, ‘showbase’, ‘showpoint’, ‘skip’, ‘split’, ‘threshold’, ‘width’]

The dir() function can also be used to list all the attributes and methods of a module. For example, the following code will print a list of all the attributes and methods of the math module:

Python

print(dir(math))

Output:

[‘doc‘, ‘file‘, ‘name‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘exp’, ‘fabs’, ‘floor’, ‘fmod’, ‘frexp’, ‘hypot’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]

The dir() function is a useful tool for exploring the capabilities of an object or module. It can be used to quickly identify all the available attributes and methods, which can be helpful for learning how to use the object or module.

Here are some additional things to keep in mind about the dir() function:

  • The dir() function will not return the values of attributes and methods, only the names.
  • The dir() function may not return all the available attributes and methods, especially for complex objects or modules.
  • The dir() function may return attributes and methods that are not intended for public use.
Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)