gpt4 book ai didi

python - 如何在 python 中发现特定包中的类?

转载 作者:太空狗 更新时间:2023-10-29 20:55:02 28 4
gpt4 key购买 nike

我有一个插件式模块包。它看起来像这样:

/Plugins /Plugins/__init__.py/Plugins/Plugin1.py/Plugins/Plugin2.py etc...

Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugins package and then search for any classes that implement PluginBaseClass. Ideally I want to be able to do something like this:

for klass in iter_plugins(project.Plugins):
action = klass()
action.run()

我看到了一些其他答案,但我的情况不同。我实际导入了基础包(即:import project.Plugins),我需要在发现模块后找到这些类。

最佳答案

编辑:这是修改后的解决方案。我意识到我在测试上一个时犯了一个错误,它并没有像你期望的那样工作。所以这是一个更完整的解决方案:

import os
from imp import find_module
from types import ModuleType, ClassType

def iter_plugins(package):
"""Receives package (as a string) and, for all of its contained modules,
generates all classes that are subclasses of PluginBaseClass."""

# Despite the function name, "find_module" will find the package
# (the "filename" part of the return value will be None, in this case)
filename, path, description = find_module(package)

# dir(some_package) will not list the modules within the package,
# so we explicitly look for files. If you need to recursively descend
# a directory tree, you can adapt this to use os.walk instead of os.listdir
modules = sorted(set(i.partition('.')[0]
for i in os.listdir(path)
if i.endswith(('.py', '.pyc', '.pyo'))
and not i.startswith('__init__.py')))
pkg = __import__(package, fromlist=modules)
for m in modules:
module = getattr(pkg, m)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if (type(klass) == ClassType and
klass is not PluginBaseClass and
issubclass(klass, PluginBaseClass)):
yield klass

我之前的解决方案是:

你可以尝试这样的事情:

from types import ModuleType
import Plugins

classes = []
for item in dir(Plugins):
module = getattr(Plugins, item)
# Get all (and only) modules in Plugins
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if isinstance(klass, PluginBaseClass):
classes.append(klass)

实际上,如果你想要一些模块化,甚至更好:

from types import ModuleType

def iter_plugins(package):
# This assumes "package" is a package name.
# If it's the package itself, you can remove this __import__
pkg = __import__(package)
for item in dir(pkg):
module = getattr(pkg, item)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if issubclass(klass, PluginBaseClass):
yield klass

关于python - 如何在 python 中发现特定包中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3507125/

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