Python Talk: The Role of __init__.py

Source: Internet
Author: User

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

1. Identify the directory as a Python module package

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. Simplified Module import Operation

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 Import test11  from Import test12  from Import test21  from Import test22  from Import test31  from 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 the directory contains __init__.py , when importing the directory with import, the code inside the __init__.py is actually executed.

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< c18/>│└──test22.py    └──subpackage_3        ├──test31.py        └──test32.py

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

Print ("you haveimported 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 Import test11

We import MyPackage to try:

Import Mypackagetraceback (most recent):   " <stdin> "  in <module>  "/home/taopeng/workspace/test/mypackage/__init__.py "  in <module> from    import'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 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 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.

>>> fromMyPackageImport*>>>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 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 test11 by default  from Import test11

Try the import again.

>>> fromMyPackageImport*>>>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.

>>> fromMypackage.subpackage_1Import*>>>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.

  

  

 

  

Python Talk: The Role of __init__.py

Related Article

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.