Understanding: if __name__ == "__main__": in Python

Understanding: if __name__ == "__main__": in Python

When you write a Python script, you often want it to behave differently when run directly versus when imported as a module. The idiom:

if __name__ == "__main__":
    # code to execute when script is run directly

lets you do exactly that.

What’s __name__?

Every Python module has a built‑in attribute called __name__.

  • When you run a file directly, __name__ is set to "__main__".
  • When you import that file, __name__ is set to the module’s filename (without .py).

Basic Example

# greet.py

def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    # This block runs only when greet.py is executed directly
    user = input("Enter your name: ")
    greet(user)

Running python greet.py prompts for your name and prints a greeting.

Importing with import greet lets you call greet.greet("Alice") without triggering the prompt.

Why Use It?

Reusability

You can put utility functions and classes at the top of the file and wrap demo or test code in the if __name__ == "__main__": block.

Testing

Quickly add simple manual tests or demo usage without interfering when the module is imported elsewhere.

Organization

Keeps script logic and importable code separate, making your codebase cleaner.

Advanced Pattern

You can also encapsulate your main logic in a function:

def main():
    user = input("Enter your name: ")
    greet(user)

if __name__ == "__main__":
    main()

This makes it easier to add command‑line argument parsing (with argparse) and unit testing around main().


Using if __name__ == "__main__": is a small habit that leads to more modular, testable, and reusable Python code. Give it a try in your next script!

Free Sample Available

Tons of Python Coding Examples!

Read More Now

Read more