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)
Sign in to answer this quiz and track your learning progress
__name__ when a Python file is run directly as a script?"**main**"NoneTrueAdvantages
- 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. - If you import this script as a module in another script, the name is set to the name of the script/module.
- Python files can act as either reusable modules, or as standalone programs.
if __name__ == "__main__":is used to execute some code only if the file is run directly, and is not being imported.
Sign in to answer this quiz and track your learning progress
if __name__ == "__main__":?