Why Python Executes Module Code on Import
In Python, importing a module does not simply load its definitions. Instead, the code contained within the module is executed upon import. This raises the question, "How can one prevent this execution?"
Stopping Module Execution on Import
The default behavior of Python stems from the fact that keywords like "class" and "def" are statements rather than declarations. This means they trigger direct execution, populating your module with functionality. To override this, the idiomatic approach employs a main function in the following format:
# Always-run code (e.g., classes, definitions) def main(): # Code to execute only when the module is run directly if __name__ == "__main__": main()
By defining a main function, you can isolate code that should only run when the module is executed as its own program (i.e., without being imported). In contrast, code placed outside the main function will run regardless of how the module is utilized.
The above is the detailed content of How Can I Prevent Python from Executing Module Code on Import?. For more information, please follow other related articles on the PHP Chinese website!