← Back to Python Course | Chapter 8: Modules & Packages | Lesson 6 of 6

Python name == 'main'

What is name?

Python automatically assigns the built-in variable __name__ to every module before running any of its code -- when you execute a file directly with 'python script.py', that file's __name__ is set to the special string __main__.

Example: What is name?

python
print(__name__)

The Main Guard

Wrapping your script's entry-point logic in 'if __name__ == "__main__":' means that code only runs when the file is executed directly, not when another file imports it -- this is the standard way to let a file be both a runnable script and a safely importable module.

Example: The Main Guard

python
def main():
    print("Running main logic")

if __name__ == "__main__":
    main()

Importing Modules

When a file is imported rather than run directly, Python sets its __name__ to the module's own name (e.g. mymodule) instead of __main__ -- printing __name__ from inside both an imported module and the script that imports it demonstrates this difference clearly.

Example: Importing Modules

python
# When this file is imported, __name__ becomes its module name
# instead of "__main__"
print(__name__)

Script vs Module

The main guard is what lets a single file define reusable functions and classes for other code to import, while also including a runnable demo or test block at the bottom that only fires when someone runs that file directly rather than importing it.

Example: Script vs Module

python
def greet():
    print("Hello from a reusable function")

if __name__ == "__main__":
    greet()  # only runs when this file is executed directly

Best Practices

Keeping top-level code (code that isn't inside any function) to a minimum and moving your actual logic into functions called from within the main guard keeps variable names from leaking into the module's namespace and makes the file's behavior easier to reason about.

Example: Best Practices

python
def run():
    print("Logic lives inside a function")

if __name__ == "__main__":
    run()
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.