Modules in Python

Source: Internet
Author: User

I. INTRODUCTION

The module supports the logical organization of Python code.

When the code is quite large, we'd better split the code into organized pieces of code, provided that they interact with each other.

The operation of attaching attributes from other modules to your module is called import, and those snippets of self-contained and organized code are modules.

If the module is a logical way to organize Python code, then the file is the method of organizing the module on the physical layer.

Therefore, a file is considered a separate module, a module can also be considered as a file, the file name of the module is the name of the module plus the extension. py.

A namespace is a collection of relational mappings from a name to an object, and module names are an important part of their property names.

The procedure for adding a name to a namespace involves binding an identifier to the specified object's operation (and adding 1 to the object's reference count).

Changing the binding of a name is called rebinding, and removing a name is called re-binding. If a function is called during execution, a local namespace is created.

Given a module name, only one module can be imported into the Python interpreter, so there is no name crossover between the different modules, so each module defines its own unique namespace.

A module can contain executable statements and function definitions, which are intended to initialize modules, which are executed only when the module name encounters the imported import statement for the first time.

The import statement can be used anywhere in the program.

After the first import, the module name is loaded into memory, and subsequent import statements only add a reference to the module object that has been loaded into memory. So when you repeat the import, there is no problem.

We can find the module that is currently loaded from Sys.modules, Sys.modules 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.

Three things to do when importing module my_module for the first time:

(1) Create a new namespace for the source file (My_module module), and the functions and methods defined in My_module are the namespaces that are accessed when using global.

(2) Execute the code contained in the module in the newly created namespace, that is, the import My_module is initially imported. The process is to put the function names in the module into the module global namespace table.

(3) Create name My_module to refer to this namespace

Second, import

1.import statements

Import a module using the import statement

Import OS Import Math

You can also import multiple modules within a row, like this

Import Os,time,random

In this way, the code is less readable than a multiline import statement.

After the interpreter finishes executing the import statement, it is loaded if the specified module is found in the search path.

This procedure follows the scope principle, if it is imported at the top level of a module, its scope is global, and if it is imported in a function, its scope is local.

If the module is imported for the first time, it will be loaded and executed.

2.from-import statements

The FROM statement is equivalent to import, and a new namespace is created, but the module's name is imported directly into the current namespace, and the name can be used directly.

 from Import time,localtime>>> time ()1510832882.9023538>>> localtime () time.struct_ Time (Tm_year=2017, tm_mon=11, tm_mday=16, tm_hour=19, tm_min=48, tm_sec=7, tm_wday=3, tm_yday=320, tm_isdst=0)

You can also import all of them, just like this

>>> Listdir ('/')['Boot','Dev','proc','Run','SYS','etc','Root','var','tmp','usr','bin','Sbin','Lib','lib64','Home','Media','mnt','opt','SRV','Backup','Python-3.6.3.tar.xz','Python-3.6.3','Script','Test','Zuoye']>>>GETCWD ()'/root'

From My_module Import * It is not a good choice to have all the names in the my_module that begin with the underscore (_) in the current position.

It "pollutes" the current namespace and is likely to overwrite existing names in the current namespace.

In both cases, it is recommended to use such a method, an occasion is: The target module has a lot of properties, repeatedly typing the module name is very inconvenient;

Another occasion is under the interactive interpreter, as this can reduce the number of inputs.

3. Extended import statement (AS)

Sometimes you import modules or module property names already in your program, or you do not want to use the imported name, you want to use the name you want to replace the original name of the module, you can use as.

Import random as Ra>>> ra.randint (10,100)30

Usage scenarios:

(1) The name of the module is too long

(2) Conflicting namespaces

(3) When the same operation is compatible with multiple modules.

Third, compile

1. Search Path of the module

The Python interpreter automatically loads some modules at startup and can be viewed using sys.modules.

>>>ImportSYS>>>sys.modules{'Builtins': <module'Builtins'(built-inch);'SYS': <module'SYS'(built-inch);'_frozen_importlib': <module'_frozen_importlib'(frozen);'_imp': <module'_imp'(built-inch);'_warnings': <module'_warnings'(built-inch);'_thread':.....

When the first import touches a module (such as My_module), it will first check whether the module has been loaded into memory (the memory of the current execution file's namespace), if any, direct reference.

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

Module Lookup Order: In-memory loaded module--"Built-in module--" Extension module--"Custom module.

After initialization, the Python program can modify the Sys.path path, and the path is placed before the priority load

2. Compiling python files

In order to increase the speed of the loading module, the speed of loading is increased rather than the speed of operation.

The Python interpreter caches the compiled version of each module in the __pycache__ directory in the following format: Module.version.pyc.

Python checks the modification time of the source file against the version of the compilation time, which needs to be recompiled if it expires.

This is a completely automated process. And the compiled module is platform independent, so the same library can be shared between different architectures of the system, that is, PYC is a cross-platform byte code.

The Python interpreter will not check the cache in one of two cases.

1. If the module is imported directly from the command line, in this way, each import is recompiled and the compiled results (python3.3) are not stored.

2. If the source file does not exist, then the cached result will not be used, if you want to use the compiled results without the source file, the compiled result must be under the source directory.

Precautions:

(1) The module name is case-sensitive, foo.py and foo.py represent two modules.

(2) You can use-O or--oo to convert Python commands to reduce the size of the compilation module.

(3) Reading instructions from the. pyc file at a speed is no faster than reading instructions in a. py file, and the. pyc file is faster when the module is clamped.

(4) You can use the import statement to automatically compile files into. pyc files, specifying run scripts on the command line or in standard input does not generate such files, so we use the Compieall module to create. pyc files for all modules in a directory.

(5) If the __name__ variable is used in the module, the name must be specified at the time of the call.

Modules in Python

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.