Python Module Import: How to Use `import` to Introduce External Functions?

In Python, we often need to use various ready-made functions to simplify code, such as performing mathematical operations, processing strings, or handling files. These functionalities are typically encapsulated in “modules,” which act like “toolboxes” filled with reusable tools (functions, variables, classes, etc.). To use these tools, we need to import the module into our current code using the import statement, which is the core concept of Python module importation.

1. What is a Module?

In simple terms, a module is a Python file (.py file) containing reusable code such as functions, variables, or classes. For example, Python’s built-in math module includes tools like sqrt (square root) and pi (pi). Your own .py files (e.g., my_utils.py) can also be considered modules.

2. Why Import Modules?

Without modules, you would need to write all functionality from scratch (e.g., calculating square roots or processing strings), leading to long and hard-to-maintain code. Importing modules allows you to reuse code written by others or yourself, significantly improving development efficiency.

3. Common Module Import Methods

Python provides several import syntaxes, each suitable for different scenarios. Here’s a detailed breakdown:

1. Basic Import: import 模块名

The most fundamental import method. After importing, use 模块名.功能名 to call the module’s tools.

Example: Import the math module to calculate a square root:

import math  # Import the math module

# Use the sqrt function (square root) from the math module
result = math.sqrt(4)
print(result)  # Output: 2.0

Explanation: math.sqrt(4) calls the sqrt function from the math module, where math is the module name and sqrt is the function name.

2. Renamed Import: import 模块名 as 别名

If the module name is long (e.g., mathematics), use as to create a shorter alias for easier subsequent calls.

Example: Alias the math module as m:

import math as m  # Import math and alias it as m

result = m.sqrt(4)
print(result)  # Output: 2.0

Use Case: Long module names (e.g., numpy) or team conventions (e.g., using np for numpy).

3. Import Specific Functionality: from 模块名 import 功能名

If you only need a specific tool from a module (e.g., just the sqrt function instead of the entire math module), import that function directly without the module prefix.

Example: Import the sqrt function from the math module:

from math import sqrt  # Import only the sqrt function

result = sqrt(4)
print(result)  # Output: 2.0

Import Multiple Functions:

from math import sqrt, pi  # Import sqrt and pi

result1 = sqrt(4)
result2 = pi
print(result1, result2)  # Output: 2.0 3.1415926...

4. Import All Functionality: from 模块名 import *

Use * to import all tools from a module, allowing direct use of function names without a prefix. However, this is not recommended due to potential naming conflicts (e.g., defining a sqrt variable would overwrite the module’s sqrt function).

Example (Not Recommended):

from math import *  # Import all functions from math

result = sqrt(4)
print(result)  # Output: 2.0

Note: * imports all non-underscore-prefixed tools, which can pollute the code namespace. Explicit imports (e.g., from math import sqrt) are preferred.

5. Import Submodules or Deeply Nested Functionality

For modules with submodules (nested module structures), import them layer by layer.

Example: The os.path submodule for file path handling:

# Method 1: Import the entire os.path submodule
import os.path

# Use os.path.exists to check if a file exists
if os.path.exists("example.txt"):
    print("File exists")

# Method 2: Import a specific function directly
from os.path import exists

if exists("example.txt"):
    print("File exists")

6. Import Custom Modules

If you wrote your own .py file (e.g., my_module.py) with functions, variables, or classes, you can import it directly.

Example:
Suppose my_module.py contains:

# my_module.py
def add(a, b):
    return a + b

PI = 3.14159

Import my_module in another Python file:

# Import the entire custom module
import my_module

sum_result = my_module.add(1, 2)
pi_value = my_module.PI
print(sum_result, pi_value)  # Output: 3 3.14159

# Import specific tools (functions/variables/classes)
from my_module import add, PI

sum_result = add(1, 2)
pi_value = PI
print(sum_result, pi_value)  # Output: 3 3.14159

Note: Custom module filenames must not conflict with Python standard library module names (e.g., avoid math.py, which would overwrite the standard math module).

4. Common Issues and Precautions

  1. Module Not Found (ImportError):
    - Cause: Python cannot locate the module.
    - Fix: Verify the filename is correct (e.g., no typos) and that the module is in the current working directory (or added to sys.path).

  2. Naming Conflicts:
    If multiple imported modules have the same function name, it will overwrite previous definitions. For example:

   from math import sqrt
   from cmath import sqrt  # Overwrites math.sqrt with cmath.sqrt
   result = sqrt(4 + 0j)  # Uses cmath.sqrt, output: 2j
  • Fix: Use aliases or explicit module references: from cmath import sqrt as csqrt.
  1. Avoid import *:
    As discussed, import * can cause naming conflicts. Explicitly import only needed tools (e.g., from math import sqrt).

5. Summary

Module importation is a core Python technique for code reuse. Master these key points:
- Basic Import: import 模块名模块名.功能名.
- Renamed Import: import 模块名 as 别名 → Simplify long names.
- Specific Import: from 模块名 import 功能名 → Directly use tools.
- Custom Module Import: Ensure no name conflicts; use import 自定义模块名 or from 自定义模块名 import 功能.

By using these import methods effectively, your code will be cleaner, more maintainable, and leverage Python’s ecosystem efficiently.

Xiaoye