Assuming all of the variables you want to save are local to the current function, you can get at them via the locals function. This is almost always a very bad idea, but it is doable.
For example:
def test():
a=1
b=2
pickle.dump(file, locals())
If you print locals(), you'll see that it's just a dict, with a key for each local variable. So, when you later load the pickle, what you'll get back is that same dict. If you want to inject it into your local environment, you can… but you have to be very careful. For example, this function:
def test2():
locals().update(pickle.load(file))
print a
… will be compiled to expect a to be a global, rather than a local, so the fact that you've updated the local a will have no effect.
This is just one of the reasons it's a bad idea to do this.
So, what's the right thing to do?
Most simply, instead of having a whole slew of variables, just have a dict with a slew of keys. Then you can pickle and unpickle the dict, and everything is trivial.
Or, alternatively, explicitly pickle and unpickle the variables you want by using a tuple:
def test():
a = 1
b = 2
pickle.dump(file, (a, b))
def test2():
a, b = pickle.load(file)
print a
In a comment, you say that you'd like to pickle a slew or variables, skipping any that can't be pickled.
To make things simpler, let's say you actually just want to pickle a dict, skipping any values that can't be pickled. (The above should show why this solution is still fully general.)
So, how do you know whether a value can be pickled? Trying to predict that is a tricky question. Even if you had a perfect list of all pickleable types, that still wouldn't help—a list full of integers can be pickled, but a list full of bound instance methods can't.
This kind of thing is exactly why EAFP ("Easier to Ask Forgiveness than Permission") is an important principle in duck-typed languages like Python.* The way to find out if something can be pickled is to pickle it, and see if you get an exception.
Here's a simple demonstration:
def is_picklable(value):
try:
pickle.dumps(value)
except TypeError:
return False
else:
return True
def filter_dict_for_pickling(d):
return {key: value for key, value in d.items() if is_picklable((key, value))}
You can make this a bit less verbose, and more efficient, if you put the whole stashing procedure in a wrapper function:
def pickle_filtered_dict(d, file):
for key, value in d.items():
pickle.dump((key, value), file)
except TypeError:
pass
def pickles(file):
try:
while True:
yield pickle.load(file)
except EOFError:
pass
def unpickle_filtered_dict(file):
return {key: value for key, value in pickles(file)}
test.aortest.bto retrieve the variable.