0
0
PythonConceptBeginner · 3 min read

__name__ == __main__ in Python: What It Means and How It Works

__name__ == '__main__' is a special condition in Python that checks if a script is run directly or imported as a module. It helps control which code runs only when the script is executed directly, not when imported.
⚙️

How It Works

In Python, every file is a module, and each module has a built-in variable called __name__. When you run a Python file directly, Python sets __name__ to the string '__main__'. But if you import that file into another script, __name__ becomes the module's name instead.

Think of it like a play: if you are the main actor performing on stage, you want to run your lines. But if you are just part of the crew helping backstage, you don't want to perform the main act. The check if __name__ == '__main__' lets your script know if it is the main actor (run directly) or just a helper (imported).

💻

Example

This example shows how the code inside the if __name__ == '__main__' block runs only when the script is executed directly.

python
def greet():
    print('Hello from greet function!')

if __name__ == '__main__':
    print('Script is running directly')
    greet()
Output
Script is running directly Hello from greet function!
🎯

When to Use

Use if __name__ == '__main__' when you want some code to run only if the script is executed directly, not when it is imported. This is useful for testing, running examples, or starting a program.

For example, if you write a module with useful functions, you can add test code inside this block. When others import your module, the test code won't run, but if you run the file yourself, it will.

Key Points

  • __name__ is a special variable set by Python.
  • __name__ == '__main__' is True only when running the script directly.
  • This check helps separate code that runs on direct execution from code that runs on import.
  • It is a common Python pattern for writing reusable and testable code.

Key Takeaways

__name__ == '__main__' checks if a Python file is run directly.
Code inside this block runs only when the script is executed, not when imported.
Use it to add test code or main program logic safely.
It helps keep modules reusable without running unwanted code on import.