dir() function
Chinese description:
You can use the built-in dir function to list module-defined identifiers. Identifiers include functions, classes, and variables.
When you provide a module name to dir(), it returns a list of names defined by the module. If no arguments are provided, it returns a list of names defined in the current module.
First, let’s look at using dir on the input sys module. We see that it contains a huge list of properties.
Next, we use the dir function without passing it an argument - by default, it returns the property list of the current module. Note that the imported modules are also part of the list.
In order to observe the effect of dir, we define a new variable a and assign a value to it, and then check dir. We observe that the same value as above is added to the list. We use the del statement to delete the variable/property in the current module, and this change is again reflected in the output of dir.
A little note about del - this statement is used to delete a variable/name after running it. In this example, del a, you will no longer be able to use the variable a - it will be as if it never existed.
Version:
This function is supported in all versions and is still available in python3.
Code example:
>>> 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(object): def __dir__(self): return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'perimeter', 'location']
English description:
dir([object])
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.
If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.
If the object does not provide __dir__(), the function tries its best to gather information from the object's __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().
The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module's attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
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.