When a Python script is imported as a module in another script, the following happens:
-
Module Loading: The Python interpreter loads the module and executes the top-level code in the imported script. This includes any function definitions, class definitions, and variable assignments.
-
__name__Variable: During this process, the special variable__name__is set to the name of the module (i.e., the filename without the.pyextension). For example, if you have a script namedmy_module.py, when it is imported,__name__will be set to"my_module". -
Code Execution: Any code that is not encapsulated within a function or class will be executed immediately upon import. However, the code block under the
if __name__ == "__main__":statement will not be executed because__name__is not equal to"__main__".
Here’s an example to illustrate this:
my_module.py
def greet():
print("Hello from my_module!")
if __name__ == "__main__":
print("This will only run if the script is executed directly.")
main_script.py
import my_module
my_module.greet()
When you run main_script.py:
- The interpreter loads
my_module.py. - It sets
__name__to"my_module", so the code underif __name__ == "__main__":does not execute. - The function
greet()is defined and can be called frommain_script.py. - The output will be:
Hello from my_module!
Summary:
- The
if __name__ == "__main__":block allows you to control which parts of your code run when the module is imported versus when it is executed directly. This is useful for testing or running specific code only when the module is not being imported elsewhere.
