enhancement request: make py3 read/write py2 pickle format
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Jun 11 05:20:43 EDT 2015
On Thursday 11 June 2015 15:39, Devin Jeanpierre wrote:
>> But I'm not talking about re-inventing what already exists. If I want
>> JSON, I'll use JSON, not spend weeks or months re-writing it from
>> scratch. I can't do this:
>>
>> class MyClass:
>>pass
>>
>> a = MyClass()
>> serialised = repr(a)
>> b = ast.literal_eval(serialised)
>> assert a == b
>
> I don't understand. You can't do that in JSON, YAML, XML, or protocol
> buffers, either. They only provide a small set of types, comparable to
> (but smaller) than the set of types you get from literal_eval/repr.
Well, what do people do when they want to serialise something like MyClass,
but have to use (say) JSON rather than pickle?
I'd write a method to export enough information (as JSON) to reconstruct the
instance, and another method to take that JSON and build an instance. If I'm
going to do all that, *I would use JSON* rather than try to create my own
format invented from scratch using only literal_eval.
Although... I suppose if I really wanted to be quick and dirty about it...
py> import ast
py> class MyClass(object): pass
...
py> a = MyClass()
py> s = repr(a.__dict__)
py> b = object.__new__(MyClass)
py> b.__dict__ = ast.literal_eval(s)
py> b
<__main__.MyClass object at 0xb725218c>
;-)
--
Steve
More information about the Python-list
mailing list