Ultimately, how to do this may be a matter of taste.
JSON
Json can be a good use because, unlike pickle, it is usable beyond python. Your object is serialized in a widely supported, easily repurposed format.
>>> import json # simple json is better bit I didn't want to force an install
>>> from collections import namedtuple
>>> Point = namedtuple("Point", "x y", verbose = False)
>>> p = Point(3,4)
>>> json.dumps(p._asdict())
'{"x": 3, "y": 4}'
>>> s = json.dumps(p._asdict())
>>> json.loads(s) # not there yet cause thisis a dict
{u'y': 4, u'x': 3} # but it is a dict that can create a Point
>>> Point(**json.loads(s))
Point(x=3, y=4)
Pickle
pickle will not work unless you define a attribute state (see __getstate__
in the docs).
This is "Nicer" in the load phase, following from above:
import pickle
# Point.__getstate__=lambda self: self._asdict() # not needed as per @simon's comment thx simon
>>> pickle.dumps(p)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nPoint\np1\nc__builtin__\ntuple\np2\n(I3\nI4\ntp3\ntp4\nRp5\nccollections\nOrderedDict\np6\n((lp7\n(lp8\nS'x'\np9\naI3\naa(lp10\nS'y'\np11\naI4\naatp12\nRp13\nb."
s = pickle.dumps(p)
>>> pickle.loads(s)
Point(x=3, y=4)
eval
I would discourage any use of eval or exec. If you do go down that route check out ast.literal_eval()
and checkout some of the SO related answers like safety of python eval