Quick mastery of usage skills of python dir function

  • 2021-08-21 20:51:48
  • OfStack

We often refer to some modules, whether it is a built-in module, a third-party module or a self-developed module, it is impossible to remember what attributes, methods and the like are in each module. If we can't remember a certain attribute in a module, we will look at the source code of the module at this time. But this is not the best way, actually the least effort-saving way is to use the dir function, this built-in function will give us the answer.

Find out what objects are in the current scope


print(dir())

Calling the builtins built-in module uses:


print(dir(__builtins__))

Check the document description of the object


print(dir.__doc__)

For beginners, it is enough to know the dir function and some concepts of introspection involved, and know the basic application of python introspection.

Extension of dir Function Usage

The dir function returns a list of properties and methods for any object,

Including module objects, function objects, string objects, list objects, dictionary objects... quite a few things.

Example of dir function:


>>> li = []
>>> dir(li)

['append','count','extend','index','insert',
'pop','remove','reverse','sort']
>>> d = {}
>>> dir(d)

['clear','copy','get','has_key','items','keys','setdefault','update','values']

Related articles: