Python Miscellaneous: _ init _. py, python _ init _. py

Source: Internet
Author: User

Python Miscellaneous: _ init _. py, python _ init _. py

We often see"_ Init _. py"What is the role of this file?

 

1. Identify the directory as a python module package)

If you use python IDE for development, if the file exists in the directory, the directory will be recognizedModule package.

2. Simplify the module Import Operation

Assume that the directory structure of our module package is as follows:

.└── 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 then 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, there are few files in this example. If the module is large and the directory is deep, you may not be able to remember how to import it. (It is very likely that, even if you only want to import a module, it will take a long time to find it in the directory)

In this case,_ Init _. pyIt is very useful. Let's take a look at how the file works.

2.1 _ init _. py?

In fact, if the directory contains_ Init _. pyWhen import is used to import the directory_ Init _. pyCode.

Add_ Init _. pyFile 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

  Mypackage/_ init _. pyAddPrintIf the file is executed, the following output is displayed:

print("You have imported mypackage")

The interaction mode is directly used below.Import

>>> import mypackageYou have imported mypackage

Apparently,_ Init _. pyThe package is imported.

2.2 Import Control Module

Let's make another experiment.Mypackage/_ init _. pyAdd the following statement:

from subpackage_1 import test11

Try importing mypackage:

>>> import mypackageTraceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/home/taopeng/Workspace/Test/mypackage/__init__.py", line 2, in <module>    from subpackage_1 import test11ImportError: No module named 'subpackage_1'

Error... What's going on?

It turns out that when we executeImportThe current directory will not change (even the files in the execution subdirectory), or the complete package name is required.

from mypackage.subpackage_1 import test11

In summary, we can_ Init _. pySpecify the modules to be imported by default

2.3 lazy import Method

Sometimes we will be lazy when importing all the content in the package.

from mypackage import *

How is this implemented?_ All __The variable does the job.

  _ All __Associated with a module list.From xx import *The modules in the list will be imported. We will_ Init _. pyTo.

__all__ = ['subpackage_1', 'subpackage_2']

Not included hereSubpackage_3To prove_ All __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__']

  Modules in the subdirectory are not imported !!!

  The import in this example is equivalent

from mypackage import subpackage_1, subpackage_2

Therefore, the import operation will continue to find_ Init _. pyAnd execute. (But not at this timeImport *)

We add_ Init _. pyFile:

_ All _ = ['test11', 'test12'] # by default, only test11from mypackage. subpackage_1 import test11 is imported.

Try importing 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 modules of the sub-package, you need to specify more accurately.

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

After learning how _ init _. py works, you should be able to understand that this file is a normal python code file.

Therefore, you can put the initialization code in this file.

  

 

 

  

 

  

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.