The Python Oracle

Why use def main()?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi

--

Chapters
00:00 Why Use Def Main()?
00:30 Accepted Answer Score 675
00:41 Answer 2 Score 8
00:54 Answer 3 Score 94
01:37 Answer 4 Score 23
01:59 Thank you

--

Full question
https://stackoverflow.com/questions/4041...

--

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.