How does it work when imported?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 25 2025
092

When a Python script is imported as a module in another script, the following happens:

  1. 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.

  2. __name__ Variable: During this process, the special variable __name__ is set to the name of the module (i.e., the filename without the .py extension). For example, if you have a script named my_module.py, when it is imported, __name__ will be set to "my_module".

  3. 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 under if __name__ == "__main__": does not execute.
  • The function greet() is defined and can be called from main_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.

0 Comments

no data
Be the first to share your comment!