DEV Community

Cover image for Python dir() function
Python64
Python64

Posted on

Python dir() function

Python dir() function returns a list of properties of a module. You can install modules with pip, but Python comes with a lot of installed modules.

To use a module, you can use the import keyword. If you want to import the os module, the syntax is: import os

If you are new to Python, you may like this book

Syntax

The dir() function syntax is:

    dir([object])

Parameter Description:

  • Object: objects, variables, types.

return value

Returns a list of properties of the module.

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

examples

The following example demonstrates the use of dir:

    >>> dir () # get a list of attributes for the current module
    [ '__Builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
    >>>
    >>> dir ([]) # view the list of methods
    [ '__Add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', ' __getslice__ ',' __gt__ ',' __hash__ ',' __iadd__ ',' __imul__ ',' __init__ ',' __iter__ ',' __le__ ',' __len__ ',' __lt__ ',' __mul__ ',' __ne__ ',' __new__ ' , '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', ' count ',' extend ',' index ',' insert ',' pop ',' remove ',' reverse ',' sort ']
    >>>

If you run dir() without arguments, it shows the methods in the current scope (see hello and okay in the returned list, scroll right)

Python 3.7.5 (default, Nov 20 2019, 09:21:52) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def hello():
...     pass
... 
>>> def okay():
...     pass
... 
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hello', 'okay']
>>> 

To look inside a module:

>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>> 

Related links:

Top comments (0)