Python's block package import

Source: Internet
Author: User

First, the module

1, what is the module

Common scenario: A module is a file that contains Python definitions and declarations, and the file name is the suffix of the module name plus the. Py.

    In fact, the import loaded module is divided into four general categories:

1 code written using Python (. py file)

2 C or C + + extensions that have been compiled as shared libraries or DLLs

3 packages for a set of modules

4 built-in modules written and linked to the Python interpreter using C

2, why to use the module

If you quit the Python interpreter and then re-enter, then the functions or variables you defined previously will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.

With the development of the program, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. At this point, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the function of reuse

3. How to use the module

3.1 Import

Sample file: spam.py, file name spam.py, module name spam

spam.pyPrint('From the spam.py') Money=1000defread1 ():Print('Spam->read1->money', Money)defread2 ():Print('Spam->read2 Calling Read') Read1 ()defChange ():Global Money Money=0

The 3.1.1 module executes only when the module name is first encountered when importing the import statement (the import statement can be used anywhere in the program, and is imported multiple times for the same module, in order to prevent you from repeating the import, the Python optimization means that the first import will The module name is loaded into memory, and subsequent import statements only add a reference to the module object that is already loaded in large memory and do not re-execute the statements within the module.

#test. Pyimport spam #只在第一次导入时才执行spam. py code, where the explicit effect is to print only once ' from the spam.py ', of course, the other top-level code is also executed, but does not show the effect. Import Spamimport spamimport spam ' execution result: from the spam.py '

We can find the module that is currently loaded from Sys.module, Sys.module is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.

3.1.2 Each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our definition in our own module global variables will be imported, and the user's global variables conflict

3.1.3 Summary: There are three things to do when you first import a module spam:

1. Create a new namespace for the source file (spam module), which is the namespace that is accessed when the functions and methods defined in spam are used in global.

2. Execute the code contained in the module in the newly created namespace, see initial import spam

3. Create a name spam to reference this namespace

3.1.4 Alias for Module name

Import spam as SM

3.1.5 importing multiple modules in one line

Import Sys,os,re

3.2 From...import ...

3.2.1 Compared to import spam, the namespace ' spam ' of the source file is brought into the current namespace and must be spam. The way of the name

The FROM statement is equivalent to import, and a new namespace is created, but the name in the spam is imported directly into the current namespace, and the name is used directly in the current namespace.

From spam import read1,read2
This way, it is good to use READ1 and read2 directly at the current location, while executing, still with the spam.py file global namespace
If there is a duplicate name read1 or read2, then there will be an overlay effect.
One particular point to emphasize is that variable assignment in Python is not a storage operation, but a binding relationship
    
3.2.2 also supports as
From spam import read1 as read
3.2.3 also supports importing multiple lines
From spam import (Read1,
                  Read2, Money                   )
3.2.4 from spam import * imports all names in spam that are not preceded by an underscore (_) into the current location, and in most cases our Python program should not use this type of import, because * you don't know what name you import, It is likely that you will overwrite the name you have defined before. And the readability is extremely poor, there is no problem when importing in an interactive environment.

    
can use __all__ to control * (to release the new version)

Add a line to the *.py

__all__=[' money ', ' read1 '] #这样在另外一个文件中用from spam import * This can import two names specified in the list

can use __all__ to control * (to release the new version)

If the name in the spam.py is pre-_money, then the From spam import *, then _money cannot be imported

3.2.5 for performance reasons, each module is imported only once, into the dictionary sys.module, if you change the contents of the module, you must restart the program, Python does not support reloading or uninstalling the previously imported modules,

3.3 Module as script execution

We can view the module name through the global variable __name__ of the module:

Run as script:
__name__ equals ' __main__ '

Import as module:
__name__=

Function: Used to control the. py file to perform different logic in different scenarios
if __name__ = = ' __main__ ':

3.4 Module Search Path

The Python interpreter automatically loads some modules at startup, and you can use Sys.modules to view

When a module is first imported (such as spam), it is first checked to see if the module has been loaded into memory (the memory that corresponds to the current execution file's namespace), and if there is a direct reference

If not, the interpreter looks for the built-in module with the same name, and then looks for the spam.py file from the list of directories given by Sys.path if it is not already found.

So the summary module lookup order is: In memory loaded modules, built-in module->sys.path path contains modules

3.5 Compiling Python files

To increase the speed at which the module is loaded. The Python interpreter caches the compiled version of each module in the __pycache__ directory, in the format: MODULE.VERSION.PYC. The version number of Python is usually included. For example, under the CPython3.3 version, the spam.py module is cached as __PYCACHE__/SPAM.CPYTHON-33.PYC. This naming convention guarantees a multi-version coexistence of compiled results.

Second, the package

A package is a way to organize the Python module namespace by using the '. Module name '.

  1. Whether it is an import or From...import form, it is the first time to be alert when you encounter a dot in an imported statement (rather than in use): This is the import syntax for packages

2. Packages are directory-level (folder-level), folders are used to form a py file (the essence of the package is a directory containing __init__.py files)

3. Import the file, the resulting namespace name from the file, import package, the name of the resulting namespace is also derived from the file, that is, the __init__.py under the package, the import package is the essence of the import of the file

Emphasize:

1. In Python3, even if there is no __init__.py file under the package, import package will still not error, and in Python2, the package must have the file, or import packet error

2. The purpose of creating the package is not to run, but to be imported to use, remember that the package is just a form of the module, the package is a module

  _init__.py file

Either way, the first time the package is imported or any other part of the package, the __init__.py file under the package is executed sequentially (we can verify it by printing a line within each package's file), which can be empty, but it can also hold some code to initialize the package.

  2.2 From GLANCE.API Import *

    When we talk about modules, we've talked about importing all from a module, where we're studying importing all * from a package.

Here is to import all from the package API, in fact, the statement will only import the package API under the __init__.py file defined in the name, we can define the __all___ in this file:

2.3 Absolute Import and relative import

    Import and relative import two ways:

Absolute import: Starting with glance

Relative import: With. Or. (can only be used in one package and not in different directories)

It is important to note that you can import the built-in or third-party modules with import (already in Sys.path), but to absolutely avoid importing the submodule of the custom package using import (not in Sys.path), you should use the From ... import ... Absolute or relative import, and the relative import of the package can only be used from the form.

2.4 Importing packages individually

Importing package names individually does not import all of the contained sub-modules in the package, such as

Python's block package import

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.