Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

What is the purpose of an `__init__.py` file, and is it still required to make a directory a package?

Answer

`__init__.py` marks a directory as a regular package and runs automatically the first time any module inside that package is imported, making it the natural place to define what the package exposes at its top level, run package-wide setup, or explicitly control `from package import *` via `__all__`. Since Python 3.3 (PEP 420), a directory without `__init__.py` can still be imported as an implicit "namespace package", which is useful for splitting a single logical package across multiple distributed directories, but an explicit `__init__.py` remains the normal, more predictable choice for an ordinary application package.

Strong answer includes

  • __init__.py runs on first import of anything inside the package
  • natural place for top-level exports, setup, or __all__
  • namespace packages (PEP 420, 3.3+) allow omitting it, but explicit is still typical

Practical example

`mypackage/__init__.py` containing

Python example
from .core import main_function

lets callers write

Python example
from mypackage import main_function

instead of the deeper

Python example
from mypackage.core import main_function

.

#packages#modules

Sources

The import systemPython Software Foundation · Module resolution, sys.path, packages and import cachingThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics