What is style if __name__ == '__main__'?

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

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

if __name__ == '__main__':
    main()

Or don’t worry about it and just write all the top-level code there:

if __name__ == '__main__':
    # all top-level code...
+4
source share
3 answers

If you write all code under protection __name__, you can never reuse this code. If, on the other hand, you put the code in a function main(), you can always import this function to another place and call it.

, setup.py setuptools, . , script, , script ( sys.path main()).

+5

, , , main , , (. ).

+4

: Python CodeAcademy.

, . "". JavaScript , . , .

JavaScript

(function() {
    // Stuff here
})();
-2

Source: https://habr.com/ru/post/1542396/


All Articles