
Use __main__.py
- Transfer
Why __init__.py is needed , probably any pythonist knows, but what about __main__.py ? I have seen many projects, either working or on Github, that do not use this magic file, although they could make their life easier. In my opinion, __main__.py is the best way to interact with Python modules consisting of several files.
But let's get it right first: how do most people run their Python scripts?
Once you write a program that you want to use both as an imported module and as a tool launched from the command line. You most likely know what is usually done in this case:
if __name__ == '__main__':
main(sys.argv)
When you feed the script to the interpreter, the magic global variable __name__ gets the value __main__ . Thus, we learn that this is not an import, but a launch. For instance:
python myapp.py
And this works great for a single file.
Problem
But if you are like me, you will not want your entire application to be crammed into a single file. Splitting logic into different files simplifies editing and support. For instance:
.
├── 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 really ? Or maybe client.py ? Where to look for the familiar string if __name__ == '__main__' ? This is where __main__.py is able to prove itself.
__main__.py
The __main__.py file is called when the project starts with the module flag - -m . And this is very convenient if the code is intended for use as a module and for launching from the console. Think of this file as a place to put everything that you usually put inside if __name__ == ' __main__' . Let's change 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 start the project as a regular module.
python -m myapp
__main__.py will be executed automatically. This is the perfect place to host the command line interface and handle input arguments!