You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.5中importlib.import_module相对模块名导入异常问题咨询

Fixing importlib.import_module Relative Import Failures in Python 3.5

Let's break down why you're seeing import failures with relative module names in Python 3.5, and how to fix it.

Common Causes of the Failure

When using a relative module name (starting with .) with importlib.import_module, two critical rules must be followed in Python 3.5:

  • The pkgname argument must be the full, exact name of an already-imported package that exists in sys.modules.
  • Truncated or incorrect package names (like your example's "tes...") will break the relative path resolution entirely.
  • Python 3.5 has stricter handling of relative imports compared to later versions—if the target package isn't already loaded into the interpreter, importlib can't resolve the relative path.

Step-by-Step Fix

First, let's align your test code with these rules. Here's the corrected version of test_impl.py:

import importlib
import sys
import test0  # Ensure the target package is loaded into sys.modules first

print(sys.version_info)

def test_imp_module(module_name, pkgname):
    try:
        _m = importlib.import_module(module_name, pkgname)
        print("import OK: module={}, pkg={}".format(module_name, pkgname))
    except Exception as e:
        print(f"Import failed: {str(e)}")

# Use the full, correct package name "test0" for pkgname
test_imp_module(".test1", "test0")
test_imp_module(".test2", "test0")

Why This Works

  1. Pre-import the package: By adding import test0, we ensure the package is registered in sys.modules—this is required for Python 3.5 to resolve relative paths using importlib.import_module.
  2. Correct pkgname: Using the full package name "test0" instead of a truncated string gives importlib a valid anchor point to locate the relative module (.test1/.test2).

Alternative: Import Without Pre-Loading the Package

If you don't want to pre-import the package, you can use importlib.util to construct the module spec manually, but this is more verbose. For most cases, pre-importing the package is the simplest and most reliable approach in Python 3.5.

内容的提问来源于stack exchange,提问作者Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:55:50