The Python interpreter knows nothing of a main()
function - the flow is just line by line.
The block that goes:
if __name__ =="__main__": main()
is a explicit call to a function if the magic variable __name__
contains the string "__main__"
. That thing, the content of __name__
is the one special thing the Python runtime does when running a module: if the current module is the main program that was invoked, it contains the string __main__
, otherwise its contents are rather the module name.
So, if you want your main
function (which can have whatever name) placed in another file, you can just import it at invocation time:
if __name__ =="__main__":
from other_module import main
main()
This feature is interesting as it allows any Python file to work both as a loadable library module by other programs, and offer standalone functionality as a program.
However, for a Python package, that is, a folder containing related .py
files, that each correspond to a module, Python has to choose which of these modules is run sequentially. When you execute a package using the -m
directive to the Python runtime, it findes a file named __main__.py
inside the package and executes that one - in the absence of such a file, the package cannot be run directly.
Follwing the same line of though, the __main__.py
file is only run automatically when executing the package as the main program - if the package, or parts of it, are imported by another program, it is not executed.
That, unlike checking the contents of __name__
with an if
expression is actually a built-in behavior that defines a starting-place.