saving and reloading variables for interactive work

Christopher T King squirrel at WPI.EDU
Wed Jul 28 15:18:30 CEST 2004

On Tue, 27 Jul 2004, Darren Dale wrote:

> If I am working interactively with 10 variables and wanted to pickle 
> them and reload them tomorrow using the same variable names, would there 
> be a direct way of doing it?

Reminds me of my days in AppleSoft BASIC :)

Unfortunately, there is no quick & easy way to do this in Python, since 
there is no easy way to differentiate unpicklable things (such as modules 
and functions) from picklable ones (your variables), nor to make Pickle 
gracefully ignore such objects.  If you can get all your variable names 
into a list, however, you could use this code:

>>> foo = 5
>>> bar = 6
>>> myvars = ['foo','bar']
>>> import pickle
>>> pickle.dump(dict([(n,vars()[n]) for n in myvars]),open('myvars','w'))

[time passes]

>>> import pickle
>>> vars().update(pickle.load(open('myvars')))
>>> foo
>>> bar

Pythonistas will cringe at my gratuitous use of vars(), but Python
currently provides no method of using getattr()/setattr() to get/set
module-level variables.  getattr(__main__,...), anyone?

More information about the Python-list mailing list