Home >Backend Development >Python Tutorial >Is `__init__.py` Still Required for Python Packages in Version 3.3 ?
Is it no longer required in Python 3.3? Provide __init__.py file for package?
Introduction: The role of the __init__.py file
In Python, the role of the __init__.py file is to identify a directory as a package. Allows the different directories and modules of this directory to be organized into a namespace. In Python 2.7 and earlier, the __init__.py file is required to create a package.
__init__.py file in Python 3.3
In Python 3.3, the concept of implicit namespace packages was introduced, which makes it possible even without __init__.py Files and packages can also be created. This means that a directory can now be designated as a namespace package and the contents of that directory can be modularized.
Use cases for namespace packages
The most common use case for this implicit namespace package feature is to allow multiple libraries from different locations to contribute sub-packages to a parent package . For example, suppose there are two libraries google_pubsub and google_storage, which provide the following structure:
google_pubsub/ # 包 1 google/ # 命名空间包(没有 __init__.py) cloud/ # 命名空间包(没有 __init__.py) pubsub/ # 常规包(有 __init__.py) __init__.py # 必需的,用于创建常规包 foo.py google_storage/ # 包 2 google/ # 命名空间包(没有 __init__.py) cloud/ # 命名空间包(没有 __init__.py) storage/ # 常规包(有 __init__.py) __init__.py # 必需的,用于创建常规包 bar.py
In this case, the google/ and google/cloud/ directories must be namespace packages, so that google_pubsub and The google_storage package is considered a sub-package under the same parent package.
Conclusion:
There are the following two types of Python packages:
The above is the detailed content of Is `__init__.py` Still Required for Python Packages in Version 3.3 ?. For more information, please follow other related articles on the PHP Chinese website!