Reputation: 169
Why is it standard in Python to have the main()
function and the if __name__ == '__main__'
check at the end of the block of code? It also seems standard for the abstraction of the functions to follow the same pattern upwards. What I mean is that the definition of the function to be executed by main()
is above the main()
and the definition of the functions inside that are above and so on..
That seems odd because when one opens the module to read the code, it ends up starting with low-level code and moves up to higher level functions. Isn't it hard to grasp what the module is doing that way?
Why not do the alternative? Have the if __name__
check at the top followed by the main()
function, and so on. This way, one quickly glances at what the main()
function does and understands what the code is about.
Upvotes: 6
Views: 6587
Reputation: 51037
The purpose of an if __name__ == '__main__':
guard is to prevent a module from having side-effects when it's imported.
The fact that it is a module rather than a script implies that it will normally be used by other code importing the definitions from it, not executed directly. So given that, it makes sense that the functions, classes and constants appear first in the source code, since those are what users of the module will be importing (and hence, what they might want to see the source of).
So even if the code guarded by if __name__ == '__main__':
doesn't rely on the definitions in the module already having been evaluated (which would be unusual), this part of the code is usually the least important to the users of the module, so it doesn't belong at the start of the file.
Upvotes: 2
Reputation: 59096
You can't call main()
before it is defined. And main
cannot call other functions before they are defined.
Example 1:
if __name__=='__main__':
main()
def main():
print("Hello")
This will error because main
hasn't been defined yet at the point where you try and execute it.
Example 2:
def main():
hello()
if __name__=='__main__':
main()
def hello():
print("Hello")
This will error because main()
is executed and tries to call hello
before it is defined.
The if __name__=='__main__':
which contains the call to main()
works best at the end of the file so that everything that it needs has been defined before it is reached.
Where you put the main
definition itself is more flexible, but putting it at the end (just before the if __name__=='__main__':
block that calls it) makes as much sense as anywhere else.
Upvotes: 12