pickle/zodb:如何处理带有类定义的移动.py文件?

Cla*_*diu 6 python refactoring pickle zodb

我正在使用ZODB它,据我所知,它pickle用于存储类实例.我正在做一些重构,我想将models.py文件拆分成几个文件.但是,如果我这样做,我认为pickle将无法找到类定义,因此将无法加载我已存储在数据库中的对象.处理这个问题的最佳方法是什么?

Mar*_*ers 5

You can create aliases; because one models.py modules is being split into multiple new modules you can only do this by importing your classes into the old location.

Both methods cause new copies of your instance pickles to refer to the new location; if you can force a write on all instances of the moved classes you don't need to retain the aliases. You can do this by setting _p_changed to True on your instances that you want to be written again.

So, to create the aliases, import your moved classes in the old location:

from newmodule1 import MyClass1, MyClass2
from newmodule2 import MyClass3
Run Code Online (Sandbox Code Playgroud)

If you only rename a module (so the same classes all are found in one new location, could be a set of imports themselves), you can also create a sys.modules entry for the old name:

import sys
import newmodule

sys.modules['full.path.to.old.module] = newmodule
Run Code Online (Sandbox Code Playgroud)