Codectionary / Developer documentation / Python

if __name__ == '__main__'

Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.

Syntax

if __name__ == '__main__':\n    # code that runs only when executed directly

Examples

Basic Usage

The standard pattern for a script that can also be safely imported.

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

if __name__ == "__main__":
    print(greet("World"))
    print("This only runs when the file is executed directly")

Script vs Module Behavior

Demonstrating the difference between running a file directly and importing it.

# calculator.py
def add(a, b):
    return a + b

if __name__ == "__main__":
    # Only runs with: python calculator.py
    print("Running calculator.py directly")
    print(add(2, 3))

# In another file:
# import calculator
# calculator.add(2, 3)  # works fine
# but "Running calculator.py directly" is NOT printed

Enabling Quick Manual Testing

Using the guard to add ad-hoc tests or demos that don't run when the module is imported elsewhere.

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

if __name__ == "__main__":
    for num in [2, 4, 7, 9, 13]:
        print(num, is_prime(num))

Best practices

  • Put your file's main execution logic inside the if __name__ == '__main__': guard so the file can be safely imported elsewhere without side effects
  • Use this pattern for any script you might also want to reuse as a library of functions in another project
  • Keep the guarded block focused on orchestration (calling functions) rather than defining new functions - definitions should be at module level
  • This is one of Python's most common idioms - expect to see it in nearly every well-structured standalone Python script

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.
File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.
os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.
datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.