The role of the Python __init__.py file

Source: Internet
Author: User

We often see the "__init__.py" file in the Python module catalog, so what does it do?

1. Module Package identification

If you are using a python-related IDE for development, the directory will be recognized as the module package if the file exists in the directory .

2. Control Guide Package Range

Let's say our module package has the following directory structure:

. └──mypackage    ├──subpackage_1    │├──test11.py    │└──test12.py    ├──subpackage_2    │├──test21.py    │└──test22.py    └──subpackage_3        ├──test31.py        └──test32.py

If we use the most direct import method, copy the entire file to the project directory and import it directly:

From mypackage.subpackage_1 import test11from mypackage.subpackage_1 import test12from mypackage.subpackage_2 Import Test21from mypackage.subpackage_2 Import test22from mypackage.subpackage_3 import Test31from mypackage.subpackage_3 Import Test32

Of course, this example file is relatively small, if the module is relatively large, the directory is deep, you may not remember how to import. (most likely, even if you just want to import a module in the directory for a long time)

In this case, the__init__.py is very useful. Let's start by looking at how the file works.

How does 2.1 __init__.py work?

In fact, if __init__.py is included in the directory, the code inside the __init__.py is executed when importing the directory with import.

We add a __init__.py file under the MyPackage directory to do an experiment:

. └──mypackage    ├──__init__.py    ├──subpackage_1    │├──test11.py    │└──test12.py    ├──subpackage_2
   │├──test21.py    │└──test22.py    └──subpackage_3        ├──test31.py        └──test32.py

  Add a printto the mypackage/__init__.py and output if the file is executed:

Print ("You have imported MyPackage")

import directly below with interactive mode

>>> import mypackageyou have imported MyPackage

It is clear that__init__.py will be executed when the package is imported.

2.2 Control Module Import

Let's do another experiment and add the following statement to the mypackage/__init__.py :

From subpackage_1 import test11

We import MyPackage to try:

>>> Import Mypackagetraceback (most recent):  File "<stdin>", line 1, in <module>  F Ile "/home/taopeng/workspace/test/mypackage/__init__.py", line 2, in <module> from    subpackage_1 Import Test11importerror:no module named ' Subpackage_1 '

An error has been made ... What's going on?

It turns out that when we execute the import , the current directory is immutable (even if it is a subdirectory file), or the full package name is required.

From mypackage.subpackage_1 import test11

In summary, we can specify the module to be imported by default in __init__.py

2.3 Lazy Ways to import

Sometimes we get lazy when we do the import, and we import all the content from the package

From mypackage Import *

How is this going to be achieved? The __all__ variable is doing the job.

  __all__ Associates a list of modules that are imported into the list when the from XX import * is executed. We will modify the __init__.py to.

__all__ = [' subpackage_1 ', ' subpackage_2 ']

The subpackage_3is not included here to prove that __all__ is working instead of importing all subdirectories.

>>> from MyPackage import *>>> dir () [' __builtins__ ', ' __doc__ ', ' __loader__ ', ' __name__ ', ' __package_ _ ', ' __spec__ ', ' subpackage_1 ', ' subpackage_2 ']>>> >>> dir (subpackage_1) [' __doc__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __path__ ', ' __spec__ ']

  The modules in the subdirectory are not imported!!!

  The import in this example is equivalent to

From MyPackage import Subpackage_1, subpackage_2

Therefore, the import operation continues to look for __init__.py in Subpackage_1 and subpackage_2 and executes. (However, import *is not executed at this time)

We add the __init__.py file under Subpackage_1:

__all__ = [' test11 ', ' test12 ']# import only test11from mypackage.subpackage_1 import test11 by default

Try the import again.

>>> from MyPackage import *>>> dir () [' __builtins__ ', ' __doc__ ', ' __loader__ ', ' __name__ ', ' __package_ _ ', ' __spec__ ', ' subpackage_1 ', ' subpackage_2 ']>>> >>> dir (subpackage_1) [' __all__ ', ' __builtins__ ' , ' __cached__ ', ' __doc__ ', ' __file__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __path__ ', ' __spec__ ', ' test11 ']

If you want to import all the modules of a child package, you need to specify more precisely.

>>> from mypackage.subpackage_1 import *>>> dir () [' __builtins__ ', ' __doc__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' test11 ', ' test12 ']
3. Configure the initialization of the module

After understanding how __init__.py works, you should be able to understand that the file is a normal Python code file.

Therefore, the initialization code can be placed in the file.

So far. Reprint please indicate the source.

The role of the Python __init__.py file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.