【问题标题】:Loading a class of unknown name in a dynamic location在动态位置加载一类未知名称
【发布时间】:2021-03-27 16:13:50
【问题描述】:

目前我正在将文件提取到操作系统的临时目录。其中一个文件是一个 Python 文件,其中包含一个我需要处理的类。 Python 的文件是已知的,但文件中的类的名称是未知的。但可以安全地假设,只有一个类,并且该类是另一个类的子类。

我尝试使用importlib,但我无法掌握课程。

到目前为止我试过了:

# Assume 
# module_name contains the name of the class and     -> "MyClass"
# path_module contains the path to the python file   -> "../Module.py"
spec = spec_from_file_location(module_name, path_module)
module = module_from_spec(spec)
for pair in inspect.getmembers(module):
    print(f"{pair[1]} is class: {inspect.isclass(pair[1])}")

当我遍历模块的成员时,它们都没有被打印为一个类。

在这种情况下,我的班级称为BasicModel,控制台上的输出如下所示:

BasicModel is class: False

解决这个问题的正确方法是什么?

编辑:

由于请求了文件的内容,请执行以下操作:

class BasicModel(Sequential):

    def __init__(self, class_count: int, input_shape: tuple):
        Sequential.__init__(self)
        self.add(Input(shape=input_shape))
        self.add(Flatten())
        self.add(Dense(128, activation=nn.relu))
        self.add(Dense(128, activation=nn.relu))
        self.add(Dense(class_count, activation=nn.softmax))

【问题讨论】:

  • 可以分享一下文件的内容,我们可以试验一下吗?
  • 我添加了文件的内容

标签: python-3.x python-importlib


【解决方案1】:

使用dir()获取文件的属性,使用inspect检查属性是否为类。如果是这样,您可以创建一个对象。

假设您的文件路径是/tmp/mysterious,您可以这样做:

import importlib
import inspect
from pathlib import Path
import sys

path_pyfile = Path('/tmp/mysterious.py')
sys.path.append(str(path_pyfile.parent))
mysterious = importlib.import_module(path_pyfile.stem)

for name_local in dir(mysterious):
    if inspect.isclass(getattr(mysterious, name_local)):
        print(f'{name_local} is a class')
        MysteriousClass = getattr(mysterious, name_local)
        mysterious_object = MysteriousClass()

【讨论】:

  • 它实际上不起作用,如果我打印出 dir() 调用的所有项目,我会得到那些 __cached__ <class 'str'> __doc__ <class 'str'> __file__ <class 'str'> __loader__ <class 'str'> __name__ <class 'str'> __package__ <class 'str'> __spec__ <class 'str'> 它们都不是 class 类型的
  • @ThomasChristopherDavies 这就是我包含 if 语句的原因。只有当 name_local 为 True 时,我们才能确定它是一个类。我添加了一行打印类名。
  • 我是否正确假设函数import_module 不采用路径作为参数?我的问题的基础是,我有一个 python 文件的路径和类的名称,我需要导入它们。同样重要的是,我只在运行时才知道这些事情。
  • @ThomasChristopherDavies 抱歉,我忽略了这一点。我编辑的答案使用了pathlibsys.path.append。可能有更好的方法来做到这一点。
  • @ThomasChristopherDavies No. path_pyfile/tmp/dir123/pyfile.py str(path_pyfile.parent) 然后是 /tmp/dir123/。但是下一行中的参数应该是path_pyfile.stem。我更正了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
  • 2018-10-27
相关资源
最近更新 更多