Last updated 1 year ago by Shane Oneillpython
We have all seen the _init.py file and know its role, but what is main.py? I have seen many Python projects either on Github or at work that do not take advantage of this magic file. In my opinion, including a main_.py is a better way to interface with multi-file python modules.
Occasionally you will write a program that is organized enough so that it can both be imported as a module to another program or run by itself through a command line interface. In this case, you are probably familiar with the following lines commonly placed at the bottom of the file:
if __name__ == '__main__':
When you run a program by calling the Python interpreter on it, the magic global variable _name gets set to main_. We can use that to know that we are not being imported as a module, but ran. For example:
This works just fine for single file projects.
If you are like me, you do not want your entire application in a single python file. Separating related logic out into their own files makes for easier editing and maintainability. For example:
But then this raises confusion to a user who just downloaded your program. Which one is the main file? Is it run.py? Or maybe client.py? What file has my precious if _name_ == ‘_main’ statement? This is where we can get a lot of value from main_.py.