Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the style guideline for if __name__ == '__main__'? [closed]

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...
like image 636
Michał Czapliński Avatar asked Mar 19 '23 11:03

Michał Czapliński


2 Answers

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).

like image 61
Martijn Pieters Avatar answered Mar 24 '23 21:03

Martijn Pieters


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).

like image 38
Ismail Badawi Avatar answered Mar 24 '23 21:03

Ismail Badawi