4

I understand the purpose of it, however I was wondering what is the most pythonic way to use if __name__ == '__main__' ?

I'm divided between putting all my code in a main() function and calling it like:

if __name__ == '__main__':
    main()

Or not bothering with that and just writing all top-level code there:

if __name__ == '__main__':
    # all top-level code...
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
Michał Czapliński
  • 1,332
  • 1
  • 14
  • 24
  • 4
    Disagree with the close votes here. This is not opinion-based if the answerer can provide evidence for why one way is better than the other as in the answers Ismail Badawi links to. – Jamie Bull May 28 '14 at 22:03

3 Answers3

5

If you write all the code under the __name__ guard, you can never re-use that code. If on the other hand you put the code in a main() function, you can always import that function elsewhere and call it.

You'd use this for console scripts registered in your setup.py when packaging your project with setuptools, for example. That way you can test your script without installing it first, and run it as a installed script (which will add dependencies to sys.path before calling your main() function).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

I don't know if one is more idiomatic than the other, but one reason to put everything in a main function and call it is that local variable lookups are faster than global variable lookups (see this question for an explanation).

Community
  • 1
  • 1
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
  • The difference is minimal, certainly for a console script where the code is run just once. It shouldn't be a big concern for 99% of the use cases. – Martijn Pieters May 28 '14 at 21:58
-2

Disclaimer: I only know a little Python from CodeAcademy.

I would go for making the main function, and then calling it. It puts your code together into a "group". JavaScript does almost the same thing, but they call it modules. They make the function, and then call it right afterward.

JavaScript example

(function() {
    // Stuff here
})();
Kayla
  • 485
  • 5
  • 14