The built-in dir()
function lists the names in the current local scope when you call it without arguments. When you call it using an object as an argument, it attempts to return a list of valid attributes for that object:
dir()
Signatures Arguments Argument Description object
The object whose attributes you want to list. Return Value
dir()
returns a list of names in the current local scope.dir()
Examples
With no arguments, to list names in the current scope:
With a built-in class object as an argument:
With a module object as an argument:
dir()
Common Use Cases
The most common use cases for the dir()
function include:
dir()
Real-World Example
Suppose you’re working on a project and need to explore the attributes and methods of a module you just imported. You can use dir()
to list everything available in the module, which can help you understand how to interact with it:
By calling dir(json)
, you get a list of available functions and classes in the json
module, which helps you understand how to use the module effectively.
dir()
in Custom Classes
You can support the dir()
function in a custom class by implementing the .__dir__()
special method. Here’s an example of a class where dir()
won’t list the non-public attributes:
In this example, the Person
class defines a .__dir__()
method that filters out the non-public attributes. With this implementation, the output of dir()
only shows the public attributes.
Tutorial
Python's Built-in Functions: A Complete ExplorationIn this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4