In-depth understanding of the file __init__.py in Python
1 Introduction
1.1 Concept of Module and Package
Modules are programs, and any Python program can be imported as a module. .py
Functions written in script files, for example, can be imported xx.py
in another module or script via . import xx
If you want to import xx.py
the function in yy
, just write it from xx import yy
. It can be seen that a module can be simply understood as a .py
file.
A package is a directory where a module resides. Unlike folders, they exist at the root of a package __init__.py
. If a folder exists in the root directory, __init__.py
the folder will be considered as a Python package, otherwise the folder is an ordinary folder.
1.2 __init__.py
Introduction to the file
__init__.py
The role of the file is to turn the folder into a Python package, and there are __init__.py
files in every package in Python. Usually __init__.py
the file is empty, but we can also add other functions to it. When we import a package, we actually import its __init__.py
files. In this way, we can __init__.py
batch import the modules we need in the file, instead of importing them one by one.
2. __init__.py
Content writing
2.1 __init__.py
File content
Take the PySolid code as an example. The directory structure of the PySolid package is as follows:
.
├── grid.py
├── point.py
└── __init__.py
__init__.py
content:
# top-level functions
from pysolid.grid import (
calc_solid_earth_tides_grid,
plot_solid_earth_tides_grid,
)
from pysolid.point import (
TIDES,
calc_solid_earth_tides_point,
plot_solid_earth_tides_point,
plot_power_spectral_density4tides,
)
__all__ = [
'__version__',
'calc_solid_earth_tides_grid',
'plot_solid_earth_tides_grid',
'TIDES',
'calc_solid_earth_tides_point',
'plot_solid_earth_tides_point',
'plot_power_spectral_density4tides',
]
2.2 __init__.py
Content Explanation
Import two functions from grid.py:
calc_solid_earth_tides_grid
plot_solid_earth_tides_grid
Import four functions from point.py:
TIDES,
calc_solid_earth_tides_point
plot_solid_earth_tides_point
plot_power_spectral_density4tides
Define variables to control the scope that external callers can call. Except for the functions in the following list, other functions cannot be used, similar to private functions or variables __init__.py
.__all__
__all__ = [
'__version__',
'calc_solid_earth_tides_grid',
'plot_solid_earth_tides_grid',
'TIDES',
'calc_solid_earth_tides_point',
'plot_solid_earth_tides_point',
'plot_power_spectral_density4tides',
]
Reference:
[1] In-depth understanding __init__.py
of
the role of [2] understanding of the establishment of __init__.py in the Python project folder