if __name__ == "__main__"

Learn why Python uses if name == 'main'. Understand its purpose, when to use it, and best practices with clear examples.

Loading...
if __name__ == "__main__"

The if __name__ == "__main__" idiom is one of Python's most common patterns. It helps distinguish between when a script is run directly versus when it is imported as a module.

Here,

  • __name__: A special variable that Python automatically sets to contain the name of the current module
  • If the script is run directly, __name__ is set to "__main__"
  • If the script is imported, __name__ is set to the module's actual filename (without the .py extension)

For example:

def main():
    print("This script is being run directly.")
 
if __name__ == "__main__":
    main()

When Run Directly:

python script.py

Output:

This script is being run directly.

When Imported:

import script

Output:

No output

Why Use It?

This idiom ensures certain code only executes when the script is run directly, not when imported.

For example:

  • A script might contain reusable functions or classes that shouldn't execute upon import.
  • Ensures clear separation of reusable logic and executable script code.

Best Practices

  • Always use a main() function: Keep the code under if __name__ == "__main__": minimal, just call a main function
  • Put imports at the top: Don't put import statements inside the if block unless necessary
  • Use it for testing: Include examples or tests that help during development
  • Keep it simple: The code block should mainly handle program entry point logic
# Good structure
import os
import sys
 
def my_function():
    """Reusable function"""
    pass
 
def main():
    """Main program entry point"""
    print("Starting program...")
    my_function()
 
if __name__ == "__main__":
    main()

Debugging Tip

You can check what __name__ contains in any module:

print(f"The value of __name__ is: {__name__}")
 
def test_function():
    print("Function called!")
 
if __name__ == "__main__":
    print("This module was run directly!")
    test_function()
else:
    print("This module was imported!")

This helps you understand exactly when and how your code is being executed.


👉 Next tutorial: Python requirements.txt File

Support my work!