Storing instances using jsonpickle

Sam Raker sam.raker at gmail.com
Thu Sep 4 00:52:40 EDT 2014


1) There are, if you want to mess around with them, ways to make pickle "smarter" about class stuff: https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-normal-class-instances . I've never worked with any of this stuff (and people don't seem to like pickle all that much), and I honestly think it might just be easier to serialize class _data_ and then either create a factory that reads in e.g. a json file and outputs class instances, or tweak __init__/__new__ to take the data as an input.
2) re: "pyson," I'm pretty sure there are serialization formats that let you do this kind of thing. I feel like I was _just_ reading about one somewhere, but scrolling back through my browser history for the last 10 days or so turns up nothing (it definitely included some kind of extension functionality, though...). You could possibly approximate something like that with e.g. JSON and some crafty en-/decoding, maybe like '"mySet: {"set": [0,1,2]}, "myTuple": {"tuple": [0,1,2]}, "myObj": {"ClassName": {"foo": "bar", "baz": "quux"}}" + a parser?

On Wednesday, September 3, 2014 10:19:07 PM UTC-4, Ned Batchelder wrote:
> On 9/3/14 6:30 PM, Josh English wrote:
> 
> > On Wednesday, September 3, 2014 1:53:23 PM UTC-7, Ned Batchelder wrote:
> 
> >
> 
> >> Pickle (and it looks like jsonpickle) does not invoke the class'
> 
> >> __init__ method when it reconstitutes objects.  Your new __init__ is not
> 
> >> being run, so new attributes it defines are not being created.
> 
> >>
> 
> >> This is one of the reasons that people avoid pickle: being completely
> 
> >> implicit is very handy, but also fragile.
> 
> >>
> 
> >
> 
> > I seem to remember having this exact same frustration when I used pickle and shelve 15 years ago. I had hoped to have another way around this. I spent over a decade trying to make an XML-based database work, in part because of this limitation.
> 
> >
> 
> > Some days I get so frustrated I think the only data structure I should ever use is a dictionary.
> 
> >
> 
> > I suppose to make this sort of thing work, I should look at creating custom json encoders and decoders.
> 
> >
> 
> 
> 
> Typically, you need to decide explicitly on a serialized representation 
> 
> for your data.  Even if it's JSON, you need to decide what that JSON 
> 
> looks like.  Then you need to write code that converts the JSON-able 
> 
> data structure (dict of lists, whatever) into your object.  Often a 
> 
> version number is a good idea so that you have some chance of using old 
> 
> data as your code changes.
> 
> 
> 
> -- 
> 
> Ned Batchelder, http://nedbatchelder.com



More information about the Python-list mailing list