Broadly speaking, it is the entry point of a python script or program and is comparable to the void main() of C++ or public static void main() of java.
Specifically, the __name__ built-in makes your module "know" whether its directly executing as a script/program or being imported as a module in another module. When its directly run, the built-in has a value of "__main__" and thus the following condition will hold true:
if__name__=="__main__":pass# do something
But if your module is being imported into another module, the above won't be executed and your module won't do anything (assuming everything else in your module are just functions and classes, and no directly executing code). But if you don't place the above if condition, then whatever is inside that block (# do something) will run each time irrespective of whether your module is executed directly or being imported.
Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable:
defmain():# do something
if__name__=="__main__":main()
Personally, I prefer to wrap the entire logic inside a main() function as a standard boilerplate while creating a runnable module. It looks more neat and readable
Broadly speaking, it is the entry point of a python script or program and is comparable to the
void main()
of C++ orpublic static void main()
of java.Specifically, the
__name__
built-in makes your module "know" whether its directly executing as a script/program or being imported as a module in another module. When its directly run, the built-in has a value of"__main__"
and thus the following condition will hold true:But if your module is being imported into another module, the above won't be executed and your module won't do anything (assuming everything else in your module are just functions and classes, and no directly executing code). But if you don't place the above if condition, then whatever is inside that block (
# do something
) will run each time irrespective of whether your module is executed directly or being imported.Personally, I prefer to wrap the entire logic inside a
main()
function as a standard boilerplate while creating a runnable module. It looks more neat and readable:I agree that it is more neat, but more than that:
For example, this
foo
function will work only if it the file is executed directly, but not if it is imported (bad, confusing and inconsistent):