Every module has a built-in __name__ attribute: when a file is run directly, Python sets that file's __name__ to the string '__main__'; when the same file is instead imported by another module, __name__ is set to the module's actual name instead. Wrapping code in this check means that code only runs when the file is executed directly, not when it's imported elsewhere purely to reuse its functions or classes, letting the same file serve as both a reusable module and a standalone script.
1Understanding __name__ == '__main__'
Every module has a built-in __name__ attribute: when a file is run directly, Python sets that file's __name__ to the string '__main__'; when the same file is instead imported by another module, __name__ is set to the module's actual name instead. Wrapping code in this check means that code only runs when the file is executed directly, not when it's imported elsewhere purely to reuse its functions or classes, letting the same file serve as both a reusable module and a standalone script.
Put any code meant only for 'running this file directly' — a demo, a command-line entry point, test invocations — inside the __name__ == '__main__' guard, so importing the file elsewhere doesn't accidentally trigger side effects like printing output or launching a server.
def greet():
print("Hello from the script")
if __name__ == "__main__":
greet()2Practical Example
Here is a real-world application of __name__ == '__main__' showing how it is used in production Python code.
# math_utils.py
def square(x):
return x * x
if __name__ == "__main__":
print("Running self-test...")
assert square(4) == 16
print("All tests passed")
# Importing this file elsewhere would NOT print anything,
# since __name__ would be 'math_utils', not '__main__'.3Best Practices
Follow these guidelines when working with __name__ == '__main__':
1. Put a script's top-level, side-effect-causing logic inside the __name__ == '__main__' guard instead of directly at module level
2. Define the file's actual reusable logic in properly named functions, and call the entry-point function from inside the guard
3. Keep imports and function/class definitions outside the guard, since those should still work when the file is imported as a module
Tip: Put any code meant only for 'running this file directly' — a demo, a command-line entry point, test invocations — inside the __name__ == '__main__' guard, so importing the file elsewhere doesn't accidentally trigger side effects like printing output or launching a server.
def greet():
print("Hello from the script")
if __name__ == "__main__":
greet()