In-depth understanding of __init__.py files in Python

1 Introduction

1.1 Concept of Module and Package

Modules are programs, and any Python program can be imported as a module. .pyFunctions written in script files, for example, can be imported xx.pyin another module or script via . import xxIf you want to import xx.pythe function in yy, just write it from xx import yy. It can be seen that a module can be simply understood as a .pyfile.

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__.pythe folder will be considered as a Python package, otherwise the folder is an ordinary folder.

1.2 __init__.pyIntroduction to the file

__init__.pyThe role of the file is to turn the folder into a Python package, and there are __init__.pyfiles in every package in Python. Usually __init__.pythe file is empty, but we can also add other functions to it. When we import a package, we actually import its __init__.pyfiles. In this way, we can __init__.pybatch import the modules we need in the file, instead of importing them one by one.

2. __init__.pyContent writing

2.1 __init__.pyFile 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__.pycontent:

# 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',
]

insert image description here

2.2 __init__.pyContent 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__.pyof
the role of [2] understanding of the establishment of __init__.py in the Python project folder

Guess you like

Origin blog.csdn.net/wokaowokaowokao12345/article/details/128934877