gpt4 book ai didi

python - 如何在 Python 中创建扩展加载器?

转载 作者:行者123 更新时间:2023-12-01 06:03:57 25 4
gpt4 key购买 nike

我想改进我正在编写的 Python 框架,让它在运行时根据模块可能具有的某些属性从某个指定文件夹枚举和加载模块。

可能是这样的属性:仅在某些元数据字段中包含特定值(如标签)的模块,或者可能仅包含从特定基类派生的类的模块。

例如,假设扩展是支持不同类型身份验证的插件 - 我希望我的框架能够在运行时发现可能的插件,而无需显式配置。

似乎这种“扩展加载”应该是可能的,并且之前可能已经做过无数次了,没有一个想要尝试的搜索查询会出现任何结果,而且我不知道一个好的方法已经实现此功能的特定项目可以从阅读其他人的方法开始。

任何关于构建这样的东西的方法的指针(或者甚至是关于以更Pythonic的方式来思考这个问题的建议)都会很棒。

最佳答案

(一个好的答案将提供概述和选项,所以不要急于接受我的快速答案。)

我在我的一个项目中执行此操作,以加载包中所有模块的类,而无需使用 import * 和硬编码名称。该代码可在 Google Code 的上下文中查看.

SPECIES = []
'''An automatically generated list of the available species types.'''

def _do_import():
'''Automatically populates SPECIES with all the modules in this
folder.

:Note:
Written as a function to prevent local variables from being
imported.
'''
import os

for _, _, files in os.walk(__path__[0]):
for filename in (file for file in files if file[0] != '_' and file[-3:] == '.py'):
modname = filename[:filename.find('.')]
mod = __import__(modname, globals(), fromlist=[])
for cls in (getattr(mod, s) for s in dir(mod)):
if cls is not Species and type(cls) is type and issubclass(cls, Species):
if getattr(cls, '_include_automatically', True):
SPECIES.append(cls)
globals()[cls.__name__] = cls

_do_import()

关于python - 如何在 Python 中创建扩展加载器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com