Question

What `if __name__ == "__main__":` Does in Python

pythonnamespacesprogram-entry-pointpython-moduleidioms

Question

In Python, what does this code do, and why would you include this if statement?

if __name__ == "__main__":
    print("Hello, World!")

More broadly, how does this pattern affect whether code runs when a file is executed directly versus imported as a module?

Short Answer

By the end of this page, you will understand what __name__ is in Python, why if __name__ == "__main__": is a common pattern, and how it prevents certain code from running when a file is imported. You will also see how this idiom is used in real projects for testing, command-line scripts, and keeping modules reusable.

Concept

In Python, every file is a module, and each module has a special built-in variable called __name__.

Its value depends on how the file is being used:

  • If the file is run directly with Python, __name__ is set to "__main__".
  • If the file is imported from another file, __name__ is set to the module's name, such as "math_tools".

That means this pattern:

if __name__ == "__main__":
    print("Hello, World!")

says:

  • Run this code only if this file is the main program being executed.
  • Do not run it if this file is being imported into another program.

This matters because Python executes top-level code in a file when that file is imported. Without this check, any print statements, test code, setup logic, or script-only behavior would run during import, which is often not what you want.

A common use is to separate:

  • reusable functions and classes
  • from script startup code

This makes your file useful both as:

  • a standalone script
  • an importable module

Mental Model

Think of a Python file as a tool box with an optional demo mode.

  • The functions and classes are the tools inside the box.
  • The if __name__ == "__main__": block is the part that says, "Only run the demo if someone opens this box directly."
  • If another file imports the box just to use the tools, the demo does not start.

So the check acts like a gate:

  • direct run → open the gate
  • import → keep the gate closed
Take Quiz

Syntax and Examples

The basic syntax is:

if __name__ == "__main__":
    # code to run only when this file is executed directly

Example 1: Direct execution vs import

# greetings.py

def say_hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    print(say_hello("World"))

If you run this file directly:

python greetings.py

Output:

Hello, World!

But if another file imports it:

# app.py
import greetings

print(greetings.say_hello("Alice"))

Output:

Hello, Alice!

Notice that Hello, World! does not print during the import. That is because the guarded block does not run.

Example 2: Using a main() function

A common style is:

def main():
    print("Program started")

if __name__ == "__main__":
    main()

This is useful because:

  • main() keeps startup logic organized
  • the if block stays small and clear
  • the file is still safe to import

Step by Step Execution

Consider this file:

# demo.py
print("File is being loaded")


def add(a, b):
    return a + b

if __name__ == "__main__":
    print("Running as main program")
    print(add(2, 3))

Case 1: Run directly

Command:

python demo.py

What happens step by step:

  1. Python starts executing demo.py.
  2. __name__ is set to "__main__".
  3. print("File is being loaded") runs.
  4. The function add is defined.
  5. Python checks if __name__ == "__main__":.
  6. The condition is True.
  7. print("Running as main program") runs.
  8. add(2, 3) returns 5.
  9. 5 is printed.

Output:

File is being loaded
Running as main program
5

Case 2: Import from another file

# other.py
import demo
print("Import finished")

What happens step by step:

  1. Python starts other.py.
  2. It reaches import demo.
  3. Python loads demo.py.
  4. Inside demo.py, __name__ is set to "demo", not "__main__".
  5. print("File is being loaded") runs.
  6. The function add is defined.
  7. Python checks if __name__ == "__main__":.
  8. The condition is False.
  9. The guarded block is skipped.
  10. Control returns to other.py.
  11. print("Import finished") runs.

Output:

File is being loaded
Import finished

This shows the key idea: importing a module executes its top-level code, but not code protected by the if __name__ == "__main__": check.

Real World Use Cases

Here are common situations where this pattern is useful:

Command-line scripts

A file may contain reusable functions but also support running from the terminal.

def convert_temperature(celsius):
    return celsius * 9 / 5 + 32

if __name__ == "__main__":
    print(convert_temperature(25))

Quick manual testing

Developers often add a small test block to try functions while building them.

def is_even(n):
    return n % 2 == 0

if __name__ == "__main__":
    print(is_even(4))
    print(is_even(7))

Keeping helper modules clean

A utility file can expose functions without running extra code on import.

Training and demos

A module can be imported in lessons or notebooks, while still providing a runnable example when executed directly.

API and application entry points

Small Python apps may define reusable logic in functions and place startup code in the __main__ block.

Take Quiz

Real Codebase Usage

In real codebases, developers often use this idiom to separate definition time from run time.

Common pattern: define functions, then call main()

def load_config():
    return {"debug": True}


def main():
    config = load_config()
    print("App started", config)


if __name__ == "__main__":
    main()

This helps with:

  • reusability: other files can import load_config() or main()
  • testability: tests can import functions without triggering app startup
  • clean imports: importing a module should not unexpectedly print, connect to services, or start work

Typical uses in projects

  • Running a script from the command line
  • Holding example usage for a module
  • Keeping debugging prints out of imports
  • Starting a batch job only when explicitly executed
  • Avoiding accidental side effects during testing

Related pattern: guard side effects

Top-level code with side effects can cause problems:

# not ideal
print("Connecting to database...")

Instead:

def connect():
    print("Connecting to database...")

if __name__ == "__main__":
    connect()

This keeps imports safer and more predictable.

Common Mistakes

Mistake 1: Thinking Python automatically runs a function called main

Python does not automatically call a function just because it is named main.

Broken expectation:

def main():
    print("Hello")

Nothing runs unless you call it:

def main():
    print("Hello")

if __name__ == "__main__":
    main()

Mistake 2: Putting important code at the top level

Broken example:

print("Starting app")

If this file is imported, that line still runs. If that is not intended, move it into a guarded block.

Mistake 3: Misspelling __name__ or __main__

Broken code:

if _name_ == "_main_":
    print("Hello")

Correct code:

if __name__ == "__main__":
    print("Hello")

Both names use double underscores on each side.

Mistake 4: Using if __name__ == "__main__": to protect definitions

Function and class definitions are usually fine at the top level. What you usually want to protect is execution, not definitions.

Good:

def helper():
    return 42

if __name__ == "__main__":
    print(helper())

Mistake 5: Assuming imports do nothing

Imports do execute top-level statements in the imported file. The __main__ check helps you control that.

Mistake 6: Writing too much logic directly inside the block

This works, but can become messy:

if __name__ == "__main__":
    name = input("Name: ")
    print(f"Hello, {name}")
    # many more lines...

A cleaner approach:

def main():
    name = input("Name: ")
    print(f"Hello, {name}")

if __name__ == "__main__":
    main()

Comparisons

ConceptWhat it doesWhen it runsBest use
Top-level codeExecutes immediately when the module is loadedOn direct run and on importDefinitions and truly necessary setup
if __name__ == "__main__": blockExecutes only for the main scriptOnly on direct runScript-only behavior
main() functionGroups startup logic into a functionOnly when explicitly calledClean organization

main() vs if __name__ == "__main__":

These are related but different:

  • main() is just a normal function name by convention.
  • if __name__ == "__main__": is the actual check that decides whether code should run.

Typical combination:

def main():
    print("Start")

if __name__ == "__main__":
    main()

Top-level code vs guarded code

print("Always runs when loaded")

if __name__ == "__main__":
    print("Runs only when executed directly")

Use top-level code mainly for:

  • imports
  • constant definitions
  • function definitions
  • class definitions

Use guarded code for:

  • starting the program
  • debugging examples
  • test runs
  • command-line behavior
Take Quiz

Cheat Sheet

if __name__ == "__main__":
    main()

Rules

  • __name__ is a special Python variable.
  • When a file is run directly, __name__ == "__main__".
  • When a file is imported, __name__ is the module name.
  • Code inside the block runs only for direct execution.

Best practice

def main():
    # startup code here
    pass

if __name__ == "__main__":
    main()

Use it for

  • command-line script entry points
  • test or demo code
  • avoiding unwanted behavior on import

Avoid

  • misspelling __name__ or __main__
  • putting too many statements directly in the block
  • assuming main() runs automatically

Remember

  • imports execute top-level code
  • guarded code does not run during import

FAQ

Why is __name__ equal to "__main__"?

Python sets __name__ to "__main__" for the file that starts execution. This lets that file know it is the main entry point.

Does Python require if __name__ == "__main__":?

No. Your program can work without it. It is used when you want code to run only on direct execution and not on import.

Does Python automatically call a main() function?

No. main() is just a normal function name. You must call it yourself, usually inside the if __name__ == "__main__": block.

What happens if I import a file without this check?

All top-level statements in that file run during import. That may cause unexpected output or side effects.

Should every Python file use this pattern?

Not necessarily. Use it when a file can be run as a script or when you need to protect script-only code from running on import.

Can I still define functions and classes outside the block?

Yes. That is the normal approach. Define reusable code at the top level and put execution logic in the guarded block.

Is this only for printing text?

No. It can protect any script-only behavior, such as parsing arguments, reading files, or starting an application.

What is the difference between a script and a module in Python?

A script is a file you run directly. A module is a file you import. The same file can be both, depending on how it is used.

Take Quiz

Mini Project

Description

Build a small Python utility module that can be used in two ways: imported by another file or run directly from the terminal. This demonstrates exactly why if __name__ == "__main__": is useful.

Goal

Create a reusable Python file that exposes a function and also runs a short demo only when executed directly.

Requirements

  • Create a function that returns the square of a number.
  • Print a demo result only when the file is run directly.
  • Import the function from another file and use it without triggering the demo output.
Take Quiz

Keep learning

Related questions

View more