Back to Blog
Python

Python __name__: Script or Module?

python **name**: Understand how Python's __name__ variable distinguishes script execution from module import, and use the if __name__ == '__main__' guard correctly.

Python__name__module importscript executionentry point
Python code showing the __name__ variable and the if __name__ == '__main__' guard, illustrating script versus module execution.

python name requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When you run a Python file directly, the interpreter sets the special variable __name__ to the string "__main__". When the same file is imported as a module, __name__ is set to the module's name—the filename without the .py extension. This single behavior underpins the if __name__ == "__main__" idiom, a pattern that lets a file work both as a reusable module and as a standalone script without unwanted side effects.

What __name__ Actually Contains

__name__ is a built-in variable that Python populates for every module. Its value depends on how the module is being used:

  • Direct execution – When you run python my_script.py, Python sets __name__ to "__main__" for that file.
  • Import – When another module imports my_script via import my_script, Python sets __name__ to "my_script".

This distinction is invisible in normal code until you inspect it. A simple print statement reveals the value:

# my_script.py print(__name__)

Running python my_script.py outputs __main__. Importing it from another module outputs my_script. The variable is always a string and always reflects the execution context.

The if __name__ == "__main__" Idiom

The most common use of __name__ is to conditionally execute code only when a file is run directly. This is the familiar guard:

# helper.py def useful_function(): return 42 if __name__ == "__main__": print(useful_function())

When you run python helper.py, the guard is true and the function is called. When you import helper from another module, the guard is false and the import does not trigger the print. This separation is essential for writing modules that are safe to import without executing test code, demos, or side effects.

Without the guard, importing the module would run the print statement at import time, which is rarely what you want in a library.

How Python Sets __name__ for Scripts and Imports

The mechanism is part of Python's module system. When the interpreter starts, it reads the script file and executes it as the __main__ module. The module's __name__ attribute is assigned before any code runs. For imported modules, the import system creates a module object and sets its __name__ based on the import statement.

For example, a package with an __init__.py has __name__ set to the package's fully qualified name. A submodule like package.submodule gets __name__ equal to "package.submodule". This naming allows the import system to track modules uniquely and supports relative imports.

The following table summarizes the common scenarios:

Execution context__name__ valueExample
Direct script"__main__"python app.py
Imported moduleModule nameimport app"app"
Package importFully qualifiedimport pkg.mod"pkg.mod"
python -m"__main__"python -m pkg.mod

Note that python -m pkg.mod executes the module as the main entry point, so its __name__ becomes "__main__" even though it is part of a package. This is why the guard works with -m as well.

Common Misconceptions and Mistakes

A frequent misunderstanding is that __name__ is only relevant in the file you run. In reality, every module has its own __name__. Another mistake is writing if __name__ == "main" (missing the underscores) or using a function call without the parentheses. The comparison must be against the exact string "__main__".

A subtler issue arises when a module is imported but the guard is placed incorrectly. For instance, if you put the guard inside a function, it will never execute at import time because the function hasn't been called. The guard must be at the top level of the module.

Another common error is relying on __name__ to detect whether a module is the main program when using multiprocessing or certain frameworks. On Windows, the multiprocessing module re-imports the main module in child processes, and the guard prevents infinite recursion. Forgetting the guard in a multiprocessing context can cause a RuntimeError or spawn endless processes.

Using __name__ in Package Entry Points

When you create a Python package, you can define a __main__.py file to make the package runnable with python -m mypackage. Inside that file, __name__ is "__main__", so the same guard works. This is a clean way to provide a command-line interface for a package without exposing it as a module attribute.

# mypackage/__main__.py from .core import main if __name__ == "__main__": main()

This pattern is common in projects that want a simple entry point. The __main__.py file is executed only when the package is invoked with -m, not when it is imported. This keeps the package importable without side effects.

Testing and Debugging with __name__

During development, you can use __name__ to run quick sanity checks without polluting the module's public interface. For example, you might place a small test harness inside the guard:

# calculator.py def add(a, b): return a + b if __name__ == "__main__": assert add(2, 3) == 5 assert add(-1, 1) == 0 print("All tests passed")

This is convenient for a single-file script, but it is not a substitute for a proper test framework. For larger projects, you should use pytest or unittest and keep the guard minimal—usually just a call to a main() function.

When debugging an import issue, you can temporarily print __name__ to see which module is being loaded and in what context. This is especially useful when a package has multiple modules and you suspect an import is executing code unexpectedly.

Operational Considerations for Production Code

The __name__ guard is not just a convenience; it is a correctness requirement for production libraries. Without it, importing a module runs all top-level code, which can cause side effects like opening network connections, reading configuration files, or writing logs. This makes the module unsafe to import in a web server or a background worker.

For long-running services, the guard also prevents code from executing at import time when the module is loaded by an application server. This keeps the import phase fast and predictable. If you need to run initialization logic only once when the module is first imported, you can do so at the top level, but that code will run for every import. The guard gives you control over when that logic runs.

Another production concern is the interaction with python -m. When you run python -m mypackage, the __main__.py file is executed with __name__ set to "__main__". If you also have a main() function in __init__.py, you must decide which one is the canonical entry point. Using __main__.py is the standard approach because it keeps the package importable and the CLI separate.

Finally, remember that __name__ is a string. Comparing it to "__main__" is cheap and safe. Avoid any attempt to modify it; the interpreter manages it and changing it can break import machinery or cause confusing behavior in frameworks that rely on the value.

In summary, __name__ is a small but critical part of Python's module system. Understanding how it behaves in direct execution, imports, and package entry points lets you write modules that are both reusable and runnable, without side effects that surprise users or production systems.

python **name**: Practical Usage and Code Examples | RYUSLOG DEV