REW

What Is If __ Name __ == '__ Main __' In Python 3?

Published Aug 29, 2025 4 min read
On this page

The if __name__ == '__main__' construct in Python is a conditional block of code that executes only when the file is run directly by the Python interpreter. It is an essential idiom for writing Python modules that can be both reusable and independently executable. This mechanism is based on the special variable __name__, which Python automatically sets depending on how a script is executed.

The core of the if __name__ == '__main__' idiom

Python's interpreter assigns a value to the special, built-in __name__ variable when it executes a script. The value is either __main__ or the name of the module, which is the filename without the .py extension.

When the file is run directly

  • What happens: If you run a Python script directly from the command line, for example, python my_script.py, the interpreter sets the __name__ variable for that script to the string '__main__'.
  • The condition evaluates to True: As a result, the if __name__ == '__main__' condition is true, and the code inside the indented block is executed. This is the intended entry point for running the program as a standalone application.

When the file is imported as a module

  • What happens: If you import the Python file as a module into another script (e.g., import my_script), the interpreter sets the __name__ variable of the imported file to the module's name, which in this case would be 'my_script'.
  • The condition evaluates to False: The if __name__ == '__main__' condition is therefore false, and the code inside the block is skipped. This prevents the script-specific code from running automatically when imported.

A practical demonstration

Consider two Python files: my_module.py and main_program.py.

my_module.py

def greeting(name):
    return f"Hello, {name}!"
# This code will only run if my_module.py is executed directly.
if __name__ == '__main__':
    print("Running my_module.py directly...")
    print(greeting("Alice"))

Use code with caution.

main_program.py

import my_module
print("Running main_program.py...")
message = my_module.greeting("Bob")
print(message)

Use code with caution.

Execution:

  1. Run my_module.py directly:``` $ python my_module.py

    
    
    
    
    
    
    
    
    
    **Output:**```
    Running my_module.py directly...
    Hello, Alice!
    

    In this case, __name__ in my_module.py is '__main__', so the if block is executed.

  2. Run main_program.py:``` $ python main_program.py

    
    
    
    
    
    
    
    
    
    **Output:**```
    Running main_program.py...
    Hello, Bob!
    

    Here, my_module.py was imported. Its __name__ variable was set to 'my_module', causing the if block to be skipped. The main_program.py is the file being run directly, so its __name__ is '__main__'.

Why is this idiom a best practice?

This structure provides a powerful way to organize code and serves several practical purposes:

  • Creates a testable and reusable module: You can include test code or example usage inside the if __name__ == '__main__' block. This allows you to run a quick test by executing the file directly, without affecting any other programs that might import your module for its functions.
  • Prevents unwanted side effects: Code that is specific to running a script (like collecting user input, parsing command-line arguments, or running a main loop) should not be executed when the file is imported. This idiom prevents such "side effect" code from running during an import.
  • Defines a clear entry point: For developers, it makes the code's intent clear. The if __name__ == '__main__' block explicitly indicates which code is designed to run when the file is the primary program.
  • Follows convention: While not strictly required, using this construct is a widely accepted Python convention that improves readability and maintainability, especially for larger applications composed of multiple modules.

Common usage with a main() function

A best practice is to define a separate main() function and call it from inside the if __name__ == '__main__' block. This keeps the global scope clean and makes the code more modular.

my_module_with_main.py

def main():
    """Main entry point for the script."""
    print("Running the main() function...")
    print(f"The result of a calculation is: {10 + 5}")
if __name__ == '__main__':
    main()

Use code with caution.

This structure is particularly useful when the logic within the if block becomes complex. By putting it into a function, you can:

  • Test the main() function: Call main() from a separate test file.
  • Call main() from elsewhere: Re-use the main() logic by importing the module and calling my_module_with_main.main().
Enjoyed this article? Share it with a friend.