01 / 21
.py .py

Modules vs. Scripts
in Python

Understand the difference between running a Python file and importing it, and how __name__ == '__main__' lets you control both.

Python

What Is a Script?

A script is a Python file you run directly from the command line or your editor. When you type python hello.py, Python reads the file top to bottom and executes every statement it finds.

# hello.py (a simple script) print("Hello, world!")

What Is a Module?

A module is a Python file whose functions, classes, or variables are imported by another file. Instead of running it directly, you bring pieces of it into your own code with the import keyword.

# math_tools.py (a module) def add(a, b): return a + b

Same File, Two Roles

Here is the key insight: every .py file can act as both a script and a module. The difference is how you launch it, not what is inside it.

my_file.py Run Directly python my_file.py Acts as a Script __name__ = '__main__' Import It import my_file Acts as a Module __name__ = 'my_file'

The __name__ Variable

Every Python file automatically gets a special variable called __name__. Python sets its value before your code runs, depending on how the file was started:

Run Directly
Python sets __name__ to the string '__main__'. This tells the file "you are the main program."
Imported
Python sets __name__ to the filename (without .py). For example, importing utils.py sets __name__ to 'utils'.

The if __name__ Guard

By checking __name__, you can write code that only runs when the file is executed directly and is skipped when imported. This is called the main guard:

# greet.py def say_hello(name): return f"Hello, {name}!" if __name__ == "__main__": print(say_hello("Alice"))

Script vs. Module at a Glance

Script Mode Module Mode
How you start it python file.py import file
__name__ value '__main__' 'file'
Top-level code runs? Yes Yes
Guarded block runs? Yes No
Typical purpose Entry point / demo Reusable library

Why This Matters

1
Code reuse: Wrapping logic in functions and guarding the demo lets other files import your work without triggering unwanted side effects.
2
Testing: You can import a module into a test file and call each function individually without the script's print statements running.
3
Professional practice: Nearly every real-world Python project uses the guard. Knowing it signals that you understand how Python actually loads code.

How to Apply the Pattern

1
Define functions/classes at the top of your file. Keep your reusable logic here.
2
Add the guard at the bottom: if __name__ == "__main__":
3
Place demo/test code inside the guarded block: function calls, print statements, example usage.
4
Test both modes: run the file directly to see the demo, and import it from another file to confirm no extra output appears.

Example 1: Simple Guard

converter.py
def celsius_to_fahrenheit(c): return c * 9 / 5 + 32 if __name__ == "__main__": temp = celsius_to_fahrenheit(100) print(f"100 C = {temp} F")
python converter.py
Prints: 100 C = 212.0 F
import converter
Nothing printed. You can call converter.celsius_to_fahrenheit(37) yourself.

Example 2: Without the Guard

bad_converter.py
def celsius_to_fahrenheit(c): return c * 9 / 5 + 32 # No guard! This runs ALWAYS: temp = celsius_to_fahrenheit(100) print(f"100 C = {temp} F")

Example 3: Two Files Working Together

math_helpers.py
def square(x): return x ** 2 def cube(x): return x ** 3 if __name__ == "__main__": print("Testing:", square(4), cube(3))
app.py
from math_helpers import square, cube result = square(5) + cube(2) print("Result:", result) # 33

Execution Flow

Python loads file.py Sets __name__ automatically __name__ == '__main__'? Yes Run guarded block executes (script mode) No Skip guarded block skipped (module mode)

What Happens on Import?

1
Python finds the file by searching sys.path (current directory, installed packages, standard library).
2
Creates a module object and sets its __name__ to the filename (without .py).
3
Executes the file top to bottom: all def, class, and top-level statements run once.
4
Caches the module in sys.modules. Subsequent imports reuse the cached version, so the file does not execute again.

Common Mistakes

No Guard at All
Putting demo code at the top level means it runs on every import, causing unwanted output or side effects.
Misspelling __main__
Writing "__Main__" or "_main_" (wrong underscores/capitalization) silently breaks the guard: the block never executes.
Logic Outside Functions
Defining variables or running calculations outside any function makes them execute on import, even with a guard elsewhere.

Summary Cheat Sheet

Concept Key Detail
Script A .py file run directly: python file.py
Module A .py file imported by another: import file
__name__ Auto-set to '__main__' (direct) or 'filename' (import)
Main Guard if __name__ == "__main__": protects script-only code
Top-level code Runs in both modes: keep it to defs and imports
sys.modules Cache: a module's code runs only on first import

Question 1 of 5

What is the value of __name__ when you run a file with python app.py?

Question 2 of 5

If utils.py contains a bare print("Loading") at the top level (no guard), what happens when another file runs import utils?

Question 3 of 5

A teammate imports stats in their own script. What problem will they encounter?

Question 4 of 5

Which of the following is the correct way to write the main guard in Python?

Question 5 of 5

When you import a module for the second time in the same Python session, what happens?