Order of execution when Python imports modules

Source: Internet
Author: User

When Python imports a module and executes an import statement, what exactly does it do? According to Python's documentation, she does the following:

The first step is to create a new module object (it may contain multiple module)

The second step is to insert the module object into the Sys.module.

The third step is to load the module's code (if necessary, it must be compiled first)

The fourth step is to execute the corresponding code in the new module.

In the third step, you first need to find out where the module program is located, in the order of the search:

The current path (as well as the Sys.path specified from the current directory), Pythonpath, and then the associated default path set by the Python installation. Because of this order, the standard module is overwritten if there is a module in the current path or pythonpath that is the same as the standard module. That is, if xml.py is present in the current directory, then when you execute the import XML, the module in the current directory is imported, not the system-standard XML. So we don't have to mess up when we usually name.

With this in hand, we can build a package that is imported as a normal module, so that you can access each module in the package directly. The package in Python2 must contain a __init__.py file. Owning this file allows the Python interpreter to use the subdirectory as a module and then import it directly through the "Import subdirectory. Module". If you do not have this file you will be treated as a normal folder, not a module.

Order of execution when Python imports modules

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.