← Home

076. Name == ' Main '

Guard code that should only run as a script, not when imported

076. Name == ’ Main ’

He splits his project into two files: ram_manager.py (the library) and main.py (the script that runs it).

First attempt — main.py does import ram_manager and immediately:

Collecting RAM stats...
⚠️  RAM above 80%!

The stats-collection code ran on import! He forgot that Python executes every top-level statement when a file is loaded.

The fix: wrap executable code in the __name__ == "__main__" guard.

# ram_manager.py

def collect_stats():
    ...

def format_report(stats):
    ...

if __name__ == "__main__":
    # Only runs when you do: python ram_manager.py
    # Does NOT run when: import ram_manager
    stats = collect_stats()
    print(format_report(stats))

Now main.py can import ram_manager and use collect_stats() and format_report() without triggering side effects.

💡 Every Python file you write should be importable without side effects. Executable code belongs inside if __name__ == "__main__":.

Learning objectives

  • Understand how name changes between script and import contexts
  • [object Object]
  • Design modules that work both as scripts and importable libraries

Key concepts

  • name
  • main
  • script vs module
  • import guard

Try it

Concept detail

name is a special variable Python sets automatically.

python myfile.py   → __name__ == '__main__'
import myfile      → __name__ == 'myfile'

The guard: if name == ‘main’: main() # only runs when executed directly, not on import

WHY it matters:

  • Without the guard: every import triggers your demo/test/startup code
  • With the guard: the file works both as a standalone script AND as a library
  • The test runner imports your file — guarded code stays silent

Pattern for every Python module you write: # — library code (always available on import) — def my_function(): … class MyClass: …

# --- script code (only when run directly) ---
if __name__ == '__main__':
    result = my_function()
    print(result)

This is why every well-structured Python CLI looks like this. psutil, requests, Flask — all importable with zero side effects.

Solution

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

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

def run_demo():
    print(greet("World"))
    print(f"2 + 3 = {add(2, 3)}")

if __name__ == "__main__":
    run_demo()
    print("Script loaded")

Tests

def test_greet_format():
    assert greet("Alice") == "Hello, Alice!"

def test_greet_capitalization():
    # broken code returns "hello, Bob" — lowercase h
    assert greet("Bob").startswith("Hello")

def test_greet_exclamation():
    # broken code returns "hello, World" — missing !
    assert greet("World").endswith("!")

def test_greet_multiple():
    assert greet("Ram") == "Hello, Ram!"
    assert greet("OS") == "Hello, OS!"

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

Resources