Why use def main()?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Melt
--
Chapters
00:00 Question
00:42 Accepted answer (Score 670)
00:57 Answer 2 (Score 265)
03:35 Answer 3 (Score 93)
04:28 Answer 4 (Score 23)
04:54 Thank you
--
Full question
https://stackoverflow.com/questions/4041...
Answer 3 links:
[What does ]: https://stackoverflow.com/questions/4191...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #codingstyle
#avk47
ACCEPTED ANSWER
Score 675
Without the main sentinel, the code would be executed even if the script were imported as a module.
ANSWER 2
Score 94
if the content of foo.py
print __name__
if __name__ == '__main__':
print 'XXXX'
A file foo.py can be used in two ways.
- imported in another file :
import foo
In this case __name__ is foo, the code section does not get executed and does not print XXXX.
- executed directly :
python foo.py
When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX
One of the use of this functionality to write various kind of unit tests within the same module.
ANSWER 3
Score 23
"What does if __name__==“__main__”: do?" has already been answered.
Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.
ANSWER 4
Score 8
Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.