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.
The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail. Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.
If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With