Tutorial

Python main function

Clear, original guide explaining python if __name__ == '__main__' with examples, best practices, and FAQs.

Drake Nguyen

Founder · System Architect

3 min read
Python main function
Python main function

Understanding python if __name__ == '__main__'

The expression python if __name__ == '__main__' (often called the "main guard") is the standard way in Python to detect whether a file is being run as a script or being imported as a module. When a module runs as the script entry point, the interpreter sets the special variable __name__ to "__main__". If the same file is imported, __name__ is the module's name instead, preventing code meant only for direct execution from running on import.

Simple python main function example

Below is a compact example demonstrating a python main function and the main guard. This shows how to define a main() and ensure it runs only when the file is executed directly.

# example_main.py
print("This runs at import time or when executed directly.")
print("__name__ is:", __name__)

def main():
    print("Running the python main function")

if __name__ == '__main__':
    main()

What does if __name__ == '__main__' mean in python?

In plain terms, the condition checks whether the current module is the top-level script. If true, the guarded block runs (the script entry point). This pattern separates module-level initialization and functions from code that should execute only when the file is invoked directly.

Using the file as a module

When you import the same file from another script, any top-level statements execute immediately, but the main() function is not invoked because __name__ is the module name, not "__main__". This prevents unwanted side effects on import and is a core practice for writing reusable modules.

# import_example.py
import example_main

print("import_example finished")

Output when importing will include the top-level prints from example_main.py but will not call main(), demonstrating the python script entry point behavior.

Why use this pattern?

  • Controls execution: It keeps startup or demo code from running when the file is imported (python import side effects).
  • Supports reuse: The file can act as both a script and a module without changing code.
  • Enables testing: Test harnesses and other modules can import functions without triggering the direct-run logic.

Best practices and common pitfalls

  • Always define functions (including main()) above the guard. If you call main() before defining it you will get NameError: name 'main' is not defined.
  • Use a descriptive main function name if helpful, but main() is conventional and signals intent clearly (python main function as module).
  • Keep side-effect code minimal at module scope. Prefer explicit initialization under the main guard to avoid unexpected behavior when importing (run module as script vs import).
  • For package-level entry points, consider using __main__.py to make the package runnable with python -m package_name.

How to use __name__ == '__main__' in python for scripts and packages

For single-file scripts, place the guard at the bottom. For packages, create a __main__.py that imports and calls the package's main function so the package becomes an executable module with python -m package.

Quick FAQ

  • Q: "what does if __name__ == '__main__' mean in python"?
    A: It checks whether the file is the program entry point, executing guarded code only when true.
  • Q: "python main function not executed when imported" — why?
    A: Because on import __name__ is the module name, so the main guard evaluates to false.
  • Q: "why use if __name__ == '__main__'"?
    A: To prevent side effects on import and to clearly mark the script entry point for execution and testing.
For more details, see the official Python documentation on module execution and the __main__ namespace.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.