Specifying a module when Unpickling
Markus Wankus
markus_wankus at hotmail.com
Thu May 8 14:26:52 EDT 2003
Hi,
I was wondering what the *correct* way to do this would be...
I have a class, say Spam, which lives in a module Eggs. My application
uses binary pickles a its method of storing data in files. So, in my
application I pickle an instance of Spam, and all is well.
Now I have another application where I want to access teh data in this
pickle. However - I am including a version of the Eggs module in an
installed package called Ham. So, to use the module Eggs, I would now say:
from Ham import Eggs
mySpam = Eggs.Spam()
Fine. Now - unpickling a Spam object will fail if the module Eggs is not
importable in the current context. I can see no way specifying to the
unpickling mechanism a search path where to find the Eggs module. How I
was going to handle this was as follows:
In my Ham package, rename the Eggs.py to __Eggs__.py (just for fun), and
have my function which does the unpickling do the following:
from Ham import __Eggs__
import cPickle
need_restore = False
if sys.modules.has_key('Eggs'):
need_restore = True
backup_key = sys.modules['Eggs']
sys.modules['Eggs'] = sys.modules['Ham.__Eggs__']
try:
fo = file(r'some_filename', 'rb')
mySpam = cPickle.Unpickler(fo).load()
return mySpam
finally:
fo.close()
if need_restore:
sys.modules['Eggs'] = backup_key
else:
del sys.modules['Eggs']
This all seems to work great, but I was wondering if I have overlooked
something. Is there a way to tell the unpickler to use a certain module?
Is what I have done above *bad* for any particular reason?
Any feedback would be welcome.
Thanks,
--
Markus
More information about the Python-list
mailing list