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

Question:

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

What is __init__.py for?

What is __main__.py?

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

Asked By: buhtz

||

Answers:

__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?

Answered By: Jeff H.

__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.

Answered By: Terry Jan Reedy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.