dir()

Returns a list of the names of an object’s attributes and methods.

Returns
A sorted list of strings.
On this page

Example

#
Python
class Player:
    def __init__(self):
        self.level = 1

    def level_up(self):
        self.level += 1

names = [name for name in dir(Player()) if not name.startswith("_")]
print(names)
print("upper" in dir("text"))
Resultsaved result, you can check it
['level', 'level_up']
True

Definition and usage

#

The dir(object) function returns a sorted list of the attribute and method names available on an object. It's a quick way to check what you can do with it, for example which methods a string or a list has.

The list also includes special double-underscore names, like __len__. It is usually worth filtering them out to see the methods meant for direct use.

Called with no argument, it returns the names defined in the current scope, which helps you check what variables exist at that point in the program.

Syntax

#
Syntax
dir(object)

Parameters

#
  • object

    optional

    The object whose attributes you want to see.

Good practices

#
  • Filter out names starting with an underscore to see only public methods.
  • For the description of a specific method, use help(), e.g. help(str.split).

Related entries

#

Spotted a mistake or missing an example? Write to us.