In this lesson, you will learn how to prevent your script’s "top-level" code from running automatically when you import that script into another file.
The Problem: Accidental Execution
When you write a Python script, you often include calls to functions at the bottom of the file to test them, like print(calculate_total(10, 20)). This works great when you run the script directly. However, Python has a rule: when you import a module, it executes every line in that module from top to bottom.
If you import your script to use one of its functions in a new project, Python will blindly run those test calls again, which can cause errors or confusing output.
The Solution: The __name__ Variable
Python provides a special built-in variable called __name__.
- When you run a file directly (e.g.,
python my_script.py), Python sets__name__to the string"__main__". - When you import that file as a module (e.g.,
import my_script), Python sets__name__to the actual filename (e.g.,"my_script").
By using an if statement, we can "guard" our test code so it only runs when we execute the file directly.
Putting it Together
Here is how you implement the main guard:
def greet(name):
return f"Hello, {name}!"
# This block only runs if you run this script directly
if __name__ == '__main__':
print("Running as a standalone script:")
print(greet("Student"))
If you import this file into another project, the greet function becomes available for use, but the code inside the if __name__ == '__main__': block will be skipped entirely. This keeps your modular code clean and prevents side effects during imports. It is the standard way to separate "library code" (functions) from "execution code" (the entry point of your program).
Key Takeaway: Use if __name__ == '__main__': to ensure your initialization and test code only executes when running a file as a script, not when importing it as a module.