⬆️ ⬇️

Use __main__.py

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.



But first, let's figure it out: how do most people run their scripts in Python?



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.



Problem



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.



__main__.py



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/



All Articles