SoFunction
Updated on 2025-03-10

Several methods for importing Python modules

In Python, module import is a very important concept, which allows developers to reuse code, segment complex programs, and utilize third-party libraries. Module import is just a Python file (usually.pyFunctions, classes, and Python in files provide a variety of ways to import modules, and various ways have their own specific application scenarios. This article will introduce in detail how to import modules in Python, including the basic concepts of modules, common import methods, import path management, and import of Python standard library and third-party library.

1. What is a module?

In Python, modules are files containing Python code. A module can contain functions, classes, variables, or execute code. The module is usually a.pyFiles can also contain__init__.pyThe directory of the file. Modules are the basics of organizing code in Python. They help split the code into multiple small parts, making the program more unitary and easy to manage.

For example, a name isThe module may contain some mathematical related functions:

# 

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Using modules in programs allows you to reuse code and maintain a clear structure.

2. Basic methods of module import

1. Use import the entire module

The most common way to import modules in Python is to useimportKeywords. This imports the entire module and can access the contents in it by the module name.

import math
print((16))  # Use the sqrt function in the math module

In this example,import mathImported from the Python standard librarymathModule. After that, you can use()CallmathIn the modulesqrtFunction to calculate square root.

2. Use from... import... to import specific content in the module

If you only need a specific function, class, or variable in the module, you can usefrom ... import ...grammar. The method only imports the specified content and does not import the entire module.

from math import sqrt
print(sqrt(16))  # Use the sqrt function directly without prefixing math

In this way,sqrtDirectly enter the current namespace, avoiding the need to add it every time you call itmath.external.

3. Use from... import * to import everything in the module

from ... import *The syntax imports all such public content in the module. Although the method is very convenient, it is generally not recommended because it can cause namespace pollution, especially in large projects.

from math import *
print(sqrt(16))  # No module prefix is ​​required, use functions directly

Although this import method is convenient, it will directly introduce all public variables, functions, classes, etc. in the module into the current namespace, which may conflict with other variables or functions in the current code.

4. Use import ... as ...module name

Sometimes the module name may be very long, or you want to give an alias to the module, which can be used at this time.import ... as ...grammar.

import math as m
print((16))  # Use the alias m to call the sqrt function in the math module

This way can make the code more concise, especially when the module name is long. For example,import numpy as npIt is a very common practice in data science, simplifying the writing of code.

5. Import different modules multiple times

In one file, you can import modules or import multiple different content from multiple modules.

import math
from datetime import datetime
print((16))
print(())

In this example,mathModules anddatetimeThe modules are imported into the current namespace.

3. Search path for module import

When you import a module, Python will look for modules in a specific search order. This search process is called "module search path". Python will look for modules in the following locations:

  • Current directory: If the module is in the current directory, Python will first look for the module in the current directory.
  • Environment variablesPYTHONPATH: If the module is not found in the current directory, Python will be in the environment variablePYTHONPATHSearch in the specified directory.
  • Standard library: If the module is still not found, Python will look for it in Python's standard library.
  • Third-party library: If the module is not in the standard library, Python will look for it in the installed third-party library (for example, bypipinstalled library).

AvailableTo view the current module search path:

import sys
print()

4. Package

This is a folder containing multiple modules. A package is a folder for organizing multiple modules, and at least one of the packages is required.__init__.pyFiles, Python tells a package, not a normal folder.

1. Import modules in packages

Suppose there is the following file structure:

my_package/
    __init__.py
    
    

You can import modules in the package in the following ways:

from my_package import module1

2. Import specific content in the package

If you only need a module or function in the package, you can directly import a function in the module or module:

from my_package.module1 import function1

5. Relative import and absolute import

1. Absolutely imported

Absolute import refers to the import path starting from the root of the project. For example:

from my_package.module1 import function1

This method starts from the root of the package and searches downward layer by layer.

2. Feedback

Relative import refers to importing other modules relative to the location of the current module. Relatively import and use.and..to represent the current directory and the previous directory.

  • .Shows the current directory.
  • ..Represents the upper directory.

For example, if you aremy_package/In, you want to import the same package, relative import can be used:

from .module2 import function2

If you want to import modules in the previous directory, you can use..

from ..module3 import function3

6. Import of Python standard library and third-party library

1. Python Standard Library

Python comes with a large number of standard libraries, which are part of the Python installation package and do not need to be installed when used. Common standard libraries areossysmathdatetimerandomwait. The method of importing these libraries is the same as that of normal modules:

import os
import sys
from datetime import datetime

2. Third-party library

In addition to the Python standard library, Python also has many third-party libraries, which can be used to manage packages.pipInstall. For example, installrequestsLibrary:

pip install requests

After the installation is complete, you can import the third-party library just like importing the standard library:

import requests
response = ('')

7. Module loading mechanism

There are two important parts for loading modules in Python:Module CacheandModule reload

1. Module Cache

In Python, whenever a module is imported, Python stores the module in memory. If you import the module again, Python will use the module in the storage directly, rather than reloading it. This mechanism can improve loading efficiency.

The cache module can be passedCheck:

import sys
print()

2. Module loading

If you modify the contents of the module and want it to take effect immediately in the program, you can use()Perform overloading:

import importlib
import my_module
(my_module)

Summarize

Module import in Python is very much a concept in Python programming. A reasonable way of importing modules can help us improve the reusability, maintainability and organization of our code. Python provides a variety of import methods, includingimportfrom ... import ...from ... import *,as well asimport ... as ...etc. These methods can be selected according to specific needs.

At the same time, it is also very important to understand Python's module search paths, package concepts, and methods of relative and absolute import. In actual development, rational organization of code structure, avoiding naming conflicts, and using appropriate module import methods are the keys to improving code quality.

This is the end of this article about the implementation of several methods of Python module import. For more related Python module import content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!