Introduction
In Python, __main__ is the name of the scope where top-level code executes. When a Python file is run directly from the command line, its special built-in variable __name__ is set to the string "__main__". However, when the file is imported as a module into another script, its __name__ is set to its own filename.
This behavior allows for a common and powerful idiom: conditionally executing a block of code only when the file is run as the main program. This is achieved with the if __name__ == "__main__": statement.
In this lab, you will learn how to use this conditional block to make your Python files more versatile, enabling them to function as both standalone scripts and reusable modules.
Understanding the Main Scope
In this step, you will learn what the __main__ scope is and see how a module's __name__ variable changes depending on how it is executed.
First, let's create a simple Python module and inspect its __name__ variable.
Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.
- Open the file
my_module.pyfrom the file explorer on the left. - Add the following code to
my_module.py. This code defines a function and then prints the value of the__name__variable.
## my_module.py
def greet(name):
print(f"Hello, {name}!")
print(f"The __name__ of my_module.py is: {__name__}")
## This block checks if the script is being run directly
if __name__ == "__main__":
print("my_module.py is being run directly.")
greet("World")
Now, let's run this file directly as a script. Open the terminal and execute the following command:
python3 my_module.py
You will see the following output. Notice that __name__ is equal to "__main__", so the code inside the if block is executed.
The __name__ of my_module.py is: __main__
my_module.py is being run directly.
Hello, World!
Next, let's see what happens when we import my_module.py into another script.
- Open the file
main.py. - Add the following code, which imports
my_moduleand calls itsgreetfunction.
## main.py
import my_module
print("Running main.py")
my_module.greet("LabEx")
Now, run main.py from the terminal:
python3 main.py
Observe the output carefully:
The __name__ of my_module.py is: my_module
Running main.py
Hello, LabEx!
When main.py imports my_module.py, the Python interpreter executes the code in my_module.py. This time, its __name__ variable is set to "my_module" (the name of the module file). Because __name__ is not "__main__", the code inside the if __name__ == "__main__": block is not executed. This demonstrates how you can separate code meant for direct execution from the reusable parts of your module.
Advantages of the Main Check
In this step, you'll explore the key advantages of using the if __name__ == "__main__": check. This simple conditional statement is fundamental to writing modular and reusable Python code.
The primary advantages are:
- Dual Functionality: It allows a Python file to act as both a reusable module that can be imported and a standalone program that can be run directly.
- Code Encapsulation: It ensures that test code, command-line entry points, or example usage snippets only run when the file is executed directly, not when it's imported by another module. This prevents unexpected side effects.
- Modularity and Reusability: By separating script-level logic from core functions, you make your functions more reusable and your code easier to test and maintain.
Let's illustrate this with a practical example. Imagine you are creating a utility module with a simple function.
- Open the file
calculator.pyfrom the file explorer on the left. - Add the following code to
calculator.py. Theaddfunction is reusable, while the code inside theifblock serves as a simple test or demonstration.
## calculator.py
def add(a, b):
"""This function adds two numbers."""
return a + b
## This block will only execute when calculator.py is run directly.
## It's a good place for tests or a simple command-line interface.
if __name__ == "__main__":
print("Running calculator.py as a standalone script for testing.")
result = add(3, 5)
print(f"A test run of add(3, 5) results in: {result}")
Run this file directly to see the test code in action:
python3 calculator.py
The output shows that the test block was executed:
Running calculator.py as a standalone script for testing.
A test run of add(3, 5) results in: 8
Now, let's reuse the add function in our main application.
- Modify
main.pyto import and use theaddfunction fromcalculator.py.
## main.py
from calculator import add
print("Using the 'add' function from the calculator module.")
sum_result = add(10, 20)
print(f"The result of add(10, 20) is: {sum_result}")
- Run
main.pyfrom the terminal:
python3 main.py
You will get the following output:
Using the 'add' function from the calculator module.
The result of add(10, 20) is: 30
As you can see, the test code from calculator.py was not executed. We successfully imported and used the add function without running the script-specific logic, demonstrating the power of the if __name__ == "__main__": check for creating clean, reusable modules.
Summary
In this lab, you learned about the __main__ scope in Python and the importance of the if __name__ == "__main__": conditional block.
You have seen that:
- A Python module's
__name__variable is set to"__main__"when the file is run directly. - When the module is imported, its
__name__is set to the module's filename. - The
if __name__ == "__main__":check allows you to write code that only executes when the file is run as a standalone script.
This powerful feature is key to writing modular and reusable Python code, enabling your files to serve as both executable programs and importable libraries. By separating script-specific logic from core functionality, you can create cleaner, more maintainable, and more professional Python applications.



