What is the difference between __init__.py and __main__.py?

PythonPython 3.x

Python Problem Overview


I know of these two questions about __init__.py and __main__.py:

https://stackoverflow.com/questions/448271

https://stackoverflow.com/questions/4042905

But I don't really understand the difference between them. Or I could say I don't understand how they interact together.

Python Solutions


Solution 1 - Python

_init_.py is run when you import a package into a running python program. For instance, import idlelib within a program, runs idlelib/__init__.py, which does not do anything as its only purpose is to mark the idlelib directory as a package. On the otherhand, tkinter/__init__.py contains most of the tkinter code and defines all the widget classes.

_main_.py is run as '_main_' when you run a package as the main program. For instance, python -m idlelib at a command line runs idlelib/__main__.py, which starts Idle. Similarly, python -m tkinter runs tkinter/__main__.py, which has this line:

from . import _test as main

In this context, . is tkinter, so importing . imports tkinter, which runs tkinter/__init__.py. _test is a function defined within that file. So calling main() (next line) has the same effect as running python -m tkinter.__init__ at the command line.

Solution 2 - Python

__init__.py, among other things, labels a directory as a python directory and lets you set variables on a package wide level.

__main__.py, among other things, is run if you try to run a compressed group of python files. __main__.py allows you to execute packages.

Both of these answers were obtained from the answers you linked. Is there something else you didn't understand about these things?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbuhtzView Question on Stackoverflow
Solution 1 - PythonTerry Jan ReedyView Answer on Stackoverflow
Solution 2 - PythonJeff H.View Answer on Stackoverflow