🕯️ Magic Note
When a Python file is executed directly, Python sets __name__ to “__main__”. When the same file is imported by another module, Python sets __name__ to the module’s name (the filename without the .py extension). This simple mechanism lets you write code that behaves differently in each situation.
- __name__ is set automatically by Python before execution
- Direct execution sets __name__ to “__main__”
- Import execution sets __name__ to the module’s name
- Use if __name__ == “__main__”: to guard code that should only run on direct execution
| Execution Method | __name__ Value |
|---|---|
| Direct run: python script.py | “__main__” |
| Import: import script | “script” |
| Import from package: from package import module | “package.module” |
| Interactive shell (REPL) | “__main__” |
Python
# Guard pattern for direct execution
def main():
print(“This is the main function”)
print(“Running the spell directly”)
if __name__ == “__main__”:
main()
# Output when run directly: This is the main function
# Output when run directly: Running the spell directly
# Output when imported: (nothing runs)
Python
# Printing __name__ in a module (save as spell.py)
# File: spell.py
print(f”__name__ is: {__name__}”)
# When run directly: python spell.py
# Output: __name__ is: __main__
# When imported: import spell
# Output: __name__ is: spell
Python
# Module with both reusable functions and test code
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == “__main__”:
print(“Testing the module:”)
print(f”add(3, 4) = {add(3, 4)}”)
print(f”multiply(3, 4) = {multiply(3, 4)}”)
# Output when run directly: Testing the module: add(3, 4) = 7 multiply(3, 4) = 12
# Output when imported: nothing prints, but add() and multiply() are available
- Forgetting the double underscores on both sides of __name__ and __main__
- Writing if __name__ = “__main__”: with single equals instead of ==
- Assuming the guard works inside functions or classes, it checks the module name, not the function context
⚡ Whisper
Every script carries a name. Called directly, it speaks its own truth. Imported, it whispers another. The name tells the role. Watch closely, and you will know who is performing and who is just part of the spell.