如何挑选包含模块和类的字典?

Emi*_*ily 7 python pickle python-3.x

我需要为字典键分配一个模块和类.然后挑选那个字典来存档.然后,加载pkl文件,然后根据该字典键值导入并实例化该类.

我试过这个:

import module_example
from module_example import ClassExample

dictionary = {'module': module_example, 'class': ClassExample)
Run Code Online (Sandbox Code Playgroud)

但它不会在pkl文件中存储对module_exmaple.py的引用.

我尝试过使用字符串而不是模块和类名的解决方法.但如果模块名称被重构或位置在路上发生变化,那将导致混乱.

无论如何直接这样做吗?以某种方式在字典中存储对模块和类的引用,然后根据该引用导入和实例化?

Kir*_*hou 2

这适用于单个班级。如果您想在多个模块和类中执行此操作,可以扩展以下代码。

module_class_writer.py

import module_example
from module_example import ClassExample

included_module = ["module_example"]
d = {}
for name, val in globals().items():
    if name in included_module:
        if "__module__" in dir(val):
            d["module"] = val.__module__
            d["class"] = name

#d = {'module': module_example, 'class': ClassExample}

import pickle
filehandler = open("imports.pkl","wb")
pickle.dump(d, filehandler)
filehandler.close()
Run Code Online (Sandbox Code Playgroud)

module_class_reader.py

import pickle
filehandler = open("imports.pkl",'rb')
d = pickle.load(filehandler)
filehandler.close()

def reload_class(module_name, class_name):
    mod = __import__(module_name, fromlist=[class_name])
    reload(mod)
    return getattr(mod, class_name)

if "class" in d and "module" in d: 
    reload(__import__(d["module"]))
    ClassExample = reload_class(d["module"], d["class"])
Run Code Online (Sandbox Code Playgroud)