而不是創建第二個並行模塊和外部依賴項的符號鏈接,請在sys.modules
中添加一個條目。爲了測試,我再醃漬類實例改名模塊
[email protected] ~/tmp $ cat oldname.py
class Foo(object):
def __init__(self):
self.name = 'bar'
[email protected] ~/tmp $ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import oldname
>>> foo = oldname.Foo()
>>> foo.name
'bar'
>>> import pickle
>>> pickle.dump(foo, open('test.pkl', 'wb'), 2)
>>> exit()
[email protected] ~/tmp $ mv oldname.py newname.py
[email protected] ~/tmp $ rm oldname.*
現在正在加載失敗
[email protected] ~/tmp $ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import newname
>>> import pickle
>>> foo = pickle.load(open('test.pkl', 'rb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/usr/lib/python2.7/pickle.py", line 1124, in find_class
__import__(module)
ImportError: No module named oldname
但是,如果我重複在sys.modules中的模塊,它的工作原理。有趣的是,類實例具有新的模塊名稱。
>>> import sys
>>> sys.modules['oldname'] = sys.modules['newname']
>>> foo = pickle.load(open('test.pkl', 'rb'))
>>> foo
<newname.Foo object at 0x7f6b837d3310>
注意事項:如果班級本身改變了很多醃菜會失敗。
即使符號鏈接也是有風險的,因爲如果您還導入了真實模塊,則會有兩個名稱空間。如果模塊使用全局狀態,可能會有麻煩。也許你可以'sys.modules ['oldname'] = sys.modules ['newname']'。 – tdelaney