When importing modules in Python, top-level code runs automatically. This can set up initial states but may cause unintended side effects. Understanding this behavior is crucial for managing module execution and avoiding unexpected consequences.
To prevent unintended execution, use the if __name__ == '__main__':
conditional block. This separates code for import from direct execution, allowing modules to be both importable and executable. The __name__
variable plays a key role in controlling module behavior.
Module Behavior and Top-Level Code
Code execution during import
- Python executes all top-level code (statements outside functions or classes) when a module is imported
- Allows module to set up initial state (initialize variables, define constants, establish connections)
- Be aware of code running during import to understand module's behavior and side effects
- Module might modify global state or perform resource-intensive tasks (file I/O, network requests)
- Unintended consequences if not carefully managed (performance impact, unexpected behavior)
- Top-level code execution contributes to the module's global scope and module namespace
Prevention of unintended execution
- Use conditional block based on
__name__
variable to control code execution when importing __name__
holds the name of current module- Set to
'__main__'
when module run directly as main program - Set to module name when imported
- Set to
- Code inside
if __name__ == '__main__':
block only runs when module executed directly, not importedif __name__ == '__main__': # Code here runs only when module is main program main()
- Separates code for import from code for direct execution
- Prevents unintended side effects during import (user interaction, resource-intensive tasks)
- Allows module to be both importable and executable (library usage vs. standalone program)
- This conditional execution serves as the entry point for script execution
Role of name variable
__name__
is a built-in Python variable holding the name of current module- Set to
'__main__'
when module run directly - Set to module name when imported
- Set to
- Checking
__name__
value controls module behavior based on usage context- Different code paths for standalone program vs. library usage
- Common use cases:
- Executing code only when run directly (running tests, command-line interface)
- Preventing code execution during import (user interaction, resource-intensive tasks)
- Conditionally importing dependencies or configuring module based on usage context
- Leverages
__name__
to create modules that are both importable and executable- Flexibility in how module can be used (library or standalone program)
- Enables modular and reusable code design