What is the use of __init__.py in Python? What is the use of the __all__ variable in it?

1. What is the use of __init__.py in Python?

__init__.pyIs a special file name used to identify a Python package (package).

In Python, a package is a folder containing several modules, which must contain a file __init__.pycalled to tell Python that this is a package and that other modules can be imported in the package.

__init__.pyFiles have several common uses:

  1. Initialization package: __init__.pyA file can contain initialization code, such as setting module-level variables or performing some necessary operations. These initialization codes are automatically executed when the package is imported.

  2. Control package imports: __init__.pyThe file can control which modules can be imported. For example, you can set a list variable in __init__.pythe file containing the names of the modules that are allowed to be imported, and then refer to this variable in other modules to limit the scope of imports.

  3. Provide package-level API: __init__.pyA file can define a package-level API, making it easier for other modules to use the package. For example, you can define a function or class in __init__.pya file , and then access the function or class directly through the package name in other modules.

In summary, __init__.pyfiles are an integral part of a Python package, used to initialize and control package imports, and to provide package-level APIs.

2. Examples

When you create a Python package mypackagenamed , you must create a __init__.pyfile named in the root directory of the package. The content of this file can be any Python code, but generally it will contain the following code:


# 在 __init__.py 中初始化包级别的变量
VERSION = '1.0.0'

# 在 __init__.py 中定义包级别的函数
def hello():
    print(f'Hello from mypackage {
      
      VERSION}!')

# 在 __init__.py 中导入其他模块
from .module1 import *
from .module2 import *

The code above defines a package mypackagecalled where:

  • VERSIONis a package-level variable that stores the version number of the package.
  • hello()is a package-level function that prints a welcome message.
  • from .module1 import *The and from .module2 import *statements import mypackageother modules in , so that the contents of these modules can be used directly mypackagein .

With this __init__.pyfile , you can use in Python import mypackageto import the entire package and use its modules and functions, for example:


import mypackage

mypackage.hello()  # 输出:Hello from mypackage 1.0.0!

Or directly import a module in the package:

from mypackage import module1

module1.some_function()  # 调用 mypackage.module1 中的某个函数

In short, __init__.pythe file can make the Python package more modular and reusable, so that different modules can work together, and can provide a unified interface to the outside world.

3. What is the __all__ list in __init__.py for?

In Python packages, __all__is an optional special variable used to define the public interface of the package or module. It is a list of strings, where each string represents the name of a public object that can be imported from the package or module. If __all__a variable , it affects from <package> import *the behavior of the statement.

Specifically, __all__the role of the list includes:

  1. Control the import content of from <package> import *the statement : When you use from <package> import *the statement, Python will import the corresponding object according to the name defined in __all__the list . If __all__the list does not exist or is empty, all public objects (that is, all _objects that do not start with ) are imported by default.
  2. Display the public interface of a package or module: Using __all__the list , you can easily display the public interface of the package or module, that is, which objects can be imported and used from outside. This helps to improve the readability and maintainability of the code, making the design and implementation of the code clearer.

For example, in the file of a package mypackagenamed __init__.py, you can define a __all__list that controls the package's public interface:


__all__ = ['module1', 'module2', 'hello']

from .module1 import *
from .module2 import *

def hello():
    print('Hello from mypackage!')

In this example, __all__the list contains the names of the three public objects module1, , andmodule2 , so when you use the statement, only these three objects will be imported, and other objects will not be imported. This helps avoid naming conflicts and accidentally importing unwanted objects.hellofrom mypackage import *

In conclusion, __all__lists are a useful tool to control the public interface of a package or module and to avoid unnecessary import and naming conflicts.

Guess you like

Origin blog.csdn.net/BigerBang/article/details/129549713