Main top-level script environment

What is it

__main__ is the name of the scope in which top-level code executes. A module’s name is set equal to __main__ when read from standard input, a script, or from an interactive prompt.

A module can discover whether it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module. When it is run as a script or with python -m but not when it is imported:

# __name__ == "__main__": check if script is run directly (not imported)
if __name__ == "__main__":  # True when run as script, False when imported
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a main.py module, the contents of which will be executed when the module is run with -m.

For example, we are developing a script designed to be used as a module, we should do:

# Example: function can be imported, but test code only runs when executed directly
def add(a, b):
    return a+b

if __name__ == "__main__":  # Only runs when file is executed, not when imported
    add(3, 5)
Quiz

Sign in to answer this quiz and track your learning progress

What is the value of __name__ when a Python file is run directly as a script?
A. The filename
B. "**main**"
C. None
D. True

Advantages

  1. Every Python module has it’s __name__ defined and if this is __main__, it implies that the module is run standalone by the user, and we can do corresponding appropriate actions.
  2. If you import this script as a module in another script, the name is set to the name of the script/module.
  3. Python files can act as either reusable modules, or as standalone programs.
  4. if __name__ == "__main__": is used to execute some code only if the file is run directly, and is not being imported.
Quiz

Sign in to answer this quiz and track your learning progress

What is the main purpose of using if __name__ == "__main__":?
A. To execute code only when the file is run directly, not when imported
B. To prevent the file from being imported
C. To make the file execute faster
D. To hide code from other modules