SoFunction
Updated on 2025-05-07

Import's main functions and usage scenarios in Python

1. Preface

Apes who have written Python must be familiar with import. But Python executes related code when importing module, do you know? What other features does Python import have? Through this article, you can thoroughly master Python import

2. Python import detailed explanation

2.1 Introduction to Python import

In Python,importYes forImport keywords for variables, functions, classes, etc. defined in modules and modulesimportThe function isExtend Python's capabilities, and allows the use of features provided by other modules in the code.

2.2 Python import example

Below isimportThe main functions and usage scenarios are given, and corresponding examples are given:

  • Import module: UseimportA complete module can be imported to use the functions defined in the module in the code. For example:
import math

print()  # usemathConstants in modulespi
  • Import specific content in the module: Usefrom module import nameSyntax can import specific functions, variables, or classes in modules for use directly in code without the need to use the module name as a prefix. For example:
from math import sqrt

print(sqrt(16))  # Use directlysqrtfunction,No use required
  • Alias ​​the imported module or content: Useimport module as aliasorfrom module import name as aliasThe syntax can specify an alias for the imported module or content to use a shorter name in the code. For example:
import numpy as np

print(([1, 2, 3]))  # Use an aliasnpreplacenumpy
  • Import everything in the module: Usefrom module import *The syntax can import everything in the module to make it directly available in the code. But this practice is not usually recommended because it can lead to naming conflicts and readability issues. For example:
from math import *

print(sin(pi/2))  # Use imported directlysinandpi,But this writing is not recommended

These areimportThe main functions and usage scenarios. By importing other modules, you can extend Python's functionality and reuse existing code. Using appropriate import methods and aliases can make the code more concise and readable.

2.3 Python import further explanation

2.3.1 Python import module

In Python, when a module is imported, the code in the module is executed. However,The code in the module will only be executed once on the first import. After that, if the same module is imported again, the Python interpreter will directly use the already loaded module without executing the code in the module again.

This behavior is to ensure that the code in the ** module will be executed only once, to avoid repeated execution of the same operation. By importing modules, we can use the functions, classes, and variables defined in it when needed, without having to re-execute the code in the module.

It is worth noting that if there are globally-level executable statements in the module (such as code other than function definitions), these statements are executed at the time of import. Therefore, the import of the module may trigger some side-effect operations, such as printing out or initializing global variables.

For example: Create

print("I'm test1, I'm executed")

def say_hello():
    print("hello world test1")

Create again

def say_hello():
    from test import test1
    test1.say_hello()

if __name__ == '__main__':
    for i  in range(10):
        say_hello()

Execute Output

I'm test1, I'm executed
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1
hello world test1

2.3.2 Python import package

In Python, when a package is imported, the package itself is not executed. The corresponding code will only be executed when using modules or objects in the package.

When importing a package, the Python interpreter will find and execute the package__init__.pydocument__init__.pyThe file can contain some initialization code to set up the environment of the package, import submodules, or perform other operations that need to be performed at the time of import. But these codesThis will only be executed once the package is first imported.

For example, suppose we have a namemy_packageThe package has the following structure:

my_package/
    __init__.py
    
    

exist__init__.pyIn the file, we can place some initialization code:

print("Executing initialization code in my_package")

# Import submodulesfrom . import module1
from . import module2

We can then import in another scriptmy_packageBag:

import my_package

print("Import completed")

Run the above script and the output is as follows:

Executing initialization code in my_package
Import completed

From the output results, it can be seen that in importmy_packageWhen packing,__init__.pyThe initialization code in the program is executed once. Then,Import completedPrinted out, indicating that the import is completed.

But note that the execution here means__init__.pyThe code in the package is executed, not all modules in the package are imported and executed. Only in usemy_packageThe corresponding code will only be executed when the specific module or object is in it.

To sum up,When importing a Python package, the code of the package itself will not be executed, and the corresponding code will be executed only when using modules or objects in the package.__init__.pyThe initialization code in the file is executed once when the package is first imported and can be used to set up the package's environment and import submodules.

3. Summary

It introduces how to use and work the import keyword in Python. Through import, you can import modules and content defined in modules, extending Python's functions. The article provides examples of importing modules, importing specific content in modules, aliasing imported modules or contents, and importing everything in modules, showing a variety of uses of import.

In addition, the article explains the feature that the module's code will only be executed once on the first import, and when importing the package__init__.pyFile initialization code. Finally, it is concluded that when importing a package, the corresponding code is executed only when using modules or objects in the package, and__init__.pyThe initialization code in the file will be executed only once the package is first imported.

This is the article about the main functions and usage scenarios of import in Python. For more related Python import content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!