Why __init__.py is needed, probably, any Pythonist knows, but what about __main__.py ? I have seen a lot of projects either working or on Github that do not use this magic file, although they could make their lives easier. In my opinion, __main__.py is the best way to interact with Python modules consisting of several files.
One day you will write a program that you want to use and as an imported module, and as a tool run from the command line. You are most likely in the course, as usually come in this case:
if __name__ == '__main__': main(sys.argv)
When you feed the script to the interpreter, the magic global variable __name__ is set to __main__ . Thus, we learn that this is not an import, but a launch. For example:
python myapp.py
And it works great for a single file.
But if you are like me, you donβt want your entire application crammed into a single file. Splitting logic into different files simplifies editing and support. For example:
. βββ README.me βββ requirements.txt βββ setup.py βββ src βββ __init__.py βββ client.py βββ logic.py βββ models.py βββ run.py
But the user who cloned the project from the repository will not understand - which of these files is the main one? Is run.py ? Or maybe client.py ? Where to look for the familiar string if __name__ == '__main__' ? This is where __main__.py can prove itself.
The __main__.py file is called when the project is started with the -m flag of the module. And this is very convenient if the code is intended both for use as a module and for launching from the console. Think of this file as a place where you can put everything that you usually put inside if __name__ == ' __main__' . Let's modify the project from the example above accordingly:
. βββ README.me βββ requirements.txt βββ setup.py βββ myapp βββ __init__.py βββ __main__.py βββ client.py βββ logic.py βββ models.py
And voila! Now you can simply run the project as a normal module.
python -m myapp
__main__.py will run automatically. This is the perfect place to put the command line interface and handle input arguments!
Source: https://habr.com/ru/post/456214/