Module Execution Flow

2 min read ·

How Python Executes a Module

When Python runs a file, it executes the code line by line from top to bottom.
Every statement is executed unless controlled by conditions.
Output:
Start Hello End

Top to Bottom Execution

Python follows a sequential execution model.
Explanation:
  • Python reads and executes each line in order
  • Functions are only executed when called

Note

Function definitions are loaded into memory, but their code runs only when the function is called.


Difference Between Running and Importing

This is a very important concept.

Case 1: Running a File Directly

File: module1.py
When you run this file directly:
This is module1 Function in module1

Case 2: Importing the Same File

File: main.py
Output:
This is module1 Function in module1
👉 Even when importing, all top level code runs automatically.

Caution

Any code written outside functions or conditions will execute during import.


Controlling Execution with name

To prevent unwanted execution during import, Python provides __name__.

Behavior

  • When file is run directly → __name__ == "__main__"
  • When imported → __name__ becomes module name

Example

File: module2.py
File: main.py
Output:
  • Nothing runs automatically

Pro Tip

Always use name == "main" in modules to avoid accidental execution during import.


Exercise

Create a file test_module.py:
  • Add a print statement
  • Add a function
  • Use name to control execution
Import it into another file and observe the behavior difference.