[Switch] [Python] __init__.py and module import in Python (the problem that the module cannot be found from import)

Module in python is a more important concept. A common situation is to write a .py file in advance, and when you need to import in another file, copy the pre-written .py file to the current directory, or add the pre-written .py file to sys.path The directory where it is located, and then import. This approach is feasible for a small number of files, but if the number of programs is large and the hierarchy is complex, it will be very difficult. Is there a way, like Java's Package, to organize multiple .py files so that they can be called uniformly externally and call each other internally? The answer is yes.


It mainly uses the concept of python's package. python __init__.py plays an important role in the package.
To understand this problem, first of all, you must know what python does when it executes the import statement. According to the python documentation , which performs the following operations:
Step 1, create a new, empty module object (it may contain multiple modules);
Step 2, insert the module object into sys.module
Step 3, load the code of the module (If necessary, it must be compiled first)
Step 4, execute the corresponding code in the new module.

When executing step 3, first find the location of the module program. The principle is:
if the name of the module to be imported is m1, the interpreter must find m1.py, which first looks in the current directory, and then in the environment Look in the variable PYTHONPATH. PYTHONPATH can be regarded as something like the system's PATH variable, which contains several directories. If PYTHONPATH is not set, or m1.py is not found, continue searching for the default path associated with python's installation settings, which is usually /usr/local/lib/python under Unix.

In fact, the order of search is: the current path (and sys.path specified from the current directory), then PYTHONPATH, then the default path relative to python's installation settings. Because of this order, if the same module as the standard module exists in the current path or PYTHONPATH, the standard module will be overwritten. That is to say, if xml.py exists in the current directory, when import xml is executed, the module in the current directory is imported instead of the system standard xml.

Knowing this, we can build a package first, import it as a normal module, and then directly access each module in this package.

The package definition in Python is very simple, and its hierarchy is the same as that of the directory where the program is located, which is similar to Java, the only difference is that the package in python must contain an __init__.py file.
For example, we can organize a package like this:

package1/
    __init__.py
    subPack1/
        __init__.py
        module_11.py
        module_12.py
        module_13.py
    subPack2/
        __init__.py
        module_21.py
        module_22.py
    ...

__init__.py can be empty as long as it If it exists, it indicates that this directory should be treated as a package. Of course, the corresponding content can also be set in __init__.py, which will be described in detail below.

Ok, now we define a function in module_11.py:

def funA():
    print "funcA in module_11"
    return

Run python in the top-level directory (that is, the directory where package1 is located, and of course, refer to the above introduction, and place package1 where the interpreter can search):

>>>from package1.subPack1.module_11 import funcA
>>>funcA()
funcA in module_11

In this way, we correctly call the functions in module_11 according to the hierarchical relationship of the package.

Careful users will find that sometimes wildcards * appear in import statements to import all elements in a module. How is this achieved?
The answer is in __init__.py. We write in the __init__.py file of subPack1

__all__ = ['module_13', 'module_12']

then enter python

>>>from package1.subPack1 import *
>>>module_11.funcA()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module_11

That is to say, when imported with *, the module in the package is restricted by __init__.py.


Well, finally, let's see how to call each other inside the package.
If you want to call the module in the same package, you can import it directly. That is to say, in module_12.py, you can use

import module_11 directly.

If it is not in the same package, for example, we want to call FuncA in module_11.py in module_21.py, it should be like this:

from module_11 package name.module_11 import funcA

 

PS.from import When the module cannot be found, create an empty __init__.py file in the corresponding folder.

Original address: https://blog.csdn.net/dutsoft/article/details/40482325

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324807828&siteId=291194637