Pickle is great, but I think it's worth mentioning literal_eval from the ast module for an even easier weighting solution if you only serialize the basic python types. This is basically a "safe" version of the notorious eval function, which allows us to evaluate the basic types of python, and not any valid python code.
Example:
>>> d = {} >>> d[0] = range(10) >>> d['1'] = {} >>> d['1'][0] = range(10) >>> d['1'][1] = 'hello' >>> data_string = str(d) >>> print data_string {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '1': {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: 'hello'}} >>> from ast import literal_eval >>> d == literal_eval(data_string) True
One of the benefits is that serialized data is just python code, so it is very human friendly. Compare this to what you would get with pickle.dumps :
>>> import pickle >>> print pickle.dumps(d) (dp0 I0 (lp1 I0 aI1 aI2 aI3 aI4 aI5 aI6 aI7 aI8 aI9 asS'1' p2 (dp3 I0 (lp4 I0 aI1 aI2 aI3 aI4 aI5 aI6 aI7 aI8 aI9 asI1 S'hello' p5 ss.
The disadvantage is that as soon as the data includes a type that is not supported by literal_ast , you will have to go to something else like etching.
Graphics Noob Jun 21 '15 at 19:42 2015-06-21 19:42
source share