Import in Python

Source: Internet
Author: User

The import operation in Python is somewhat similar to # include in the C language, but it is quite different. In the C language, #include是编译前将另一个文件包含进当前文件中. Importing in Python is not just inserting one file text into another file.

Import is actually a run-time operation, and the first time the program is imported, it performs three steps.


1 Module Files found


2 compile into a bit code when needed


3 executing the code of the module to create the object it defines


These three steps are only executed when the module is imported for the first time, and then when the same module is imported, the three steps are skipped, and only the module objects loaded in memory are extracted.


Python stores the loaded modules in a table named Sys.modules, which is checked when the module is imported, and does not start the three steps above if the module exists in the table.


The module file referenced after the import statement has no file path and no file suffix. How did Python find the module and import it into the file?

The original python has a sys.path system variable that stores the search path to the import statement. This search path consists mainly of four parts:

1 Program's Home directory


2 Pythonpath Directory


3 Standard link library catalog


4 contents of any. pth file



The suffix of the import file is intentionally omitted from the import statement. Python selects the first file in the search path that matches the import file name.


In addition, the import can also use the hook program to let import when importing files to do a variety of useful things. The specific hook function is the built-in __import__ function, see the relevant manual for specific usage.

Import in Python

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.