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
pkgnameargument must be the full, exact name of an already-imported package that exists insys.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,
importlibcan'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
- Pre-import the package: By adding
import test0, we ensure the package is registered insys.modules—this is required for Python 3.5 to resolve relative paths usingimportlib.import_module. - Correct pkgname: Using the full package name
"test0"instead of a truncated string givesimportliba 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
相关产品推荐
相关产品推荐

