面试题答案
一键面试实现思路
- 创建元路径导入器类:该类需要实现
find_spec
方法,这个方法是元路径导入机制的核心,用于查找模块的规格说明(ModuleSpec
)。 - 在
find_spec
方法中:- 检查要导入的模块名称是否符合要求。
- 从数据库中读取相应的Python代码。
- 创建一个
ModuleSpec
对象,该对象包含如何创建模块的信息。
- 将自定义导入器添加到
sys.meta_path
:这样Python在导入模块时会使用自定义导入器进行查找。
关键代码片段
import sys
import types
from importlib.abc import MetaPathFinder, Loader
from importlib.machinery import ModuleSpec
# 模拟从数据库获取代码
def get_code_from_db(module_name):
# 这里应该是实际从数据库查询并返回代码的逻辑
# 示例返回一个简单的模块代码
if module_name == 'example_module':
return "def example_function(): return 'Hello from example module'"
return None
class DatabaseMetaPathFinder(MetaPathFinder):
def find_spec(self, fullname, path, target=None):
code = get_code_from_db(fullname)
if code is not None:
def exec_module(module):
exec(code, module.__dict__)
return ModuleSpec(fullname, Loader(exec_module=exec_module))
return None
sys.meta_path.append(DatabaseMetaPathFinder())
在上述代码中:
get_code_from_db
函数模拟从数据库获取代码的逻辑。DatabaseMetaPathFinder
类实现了MetaPathFinder
接口,find_spec
方法负责查找模块规格说明。- 最后将
DatabaseMetaPathFinder
的实例添加到sys.meta_path
,使自定义导入器生效。
之后就可以像导入普通模块一样导入从数据库获取代码的模块,例如:
import example_module
print(example_module.example_function())