You can find variable's name by examining environment where it's defined. Here you have two functions exploring this idea, one for pickling, one for unpickling.
You need to pass the environment to the pickling function in order to find out variables names, create a dictionary mapping the names to variables and, eventually, pickle the dictionary containing variables and their names.
The unpickling function will update the environment (usually locals()
) you pass to it with unpickled variables from your file.
import pickle
def pickle_vars(fileName, env, *vs):
d = dict([(x, env[x]) for v in vs for x in env if v is env[x]])
with open(fileName, 'wb') as f:
pickle.dump(d, f)
def unpickle_vars(fileName, env):
with open(fileName, 'rb') as f:
d = pickle.load(f)
env.update(d)
def f():
x = 10
y = 20
pickle_vars('vars', locals(), x, y)
f()
unpickle_vars('vars', globals())
print x,y
Here is a modified function to pickle each variable in separate file, named as the variable with extension .p
:
def pickle_vars(fileName, env, *vs):
d = [(x, env[x]) for v in vs for x in env if v is env[x]]
for name, var in d:
with open(name + '.p', 'wb') as f:
pickle.dump(var, f)