Hacker News new | ask | show | jobs
by XorNot 1459 days ago
The normal way to handle this is to deserialize into your application specific type, and store extraneous data in an extra field that is private but included in reserializations.

Because your application will fail if fields you need aren't there.

1 comments

That can turn into an enormous amount of work to provide all the permutations of type conversions between 3+ classes, and then manually shuffle between them over and over. It's even harder when you don't have the power to add similar conversions for the classes you're trying to convert to/from.

Classes aren't a great abstraction when enforcing program invariants like "this object must at least have fields a and b." With a dict you can just have "dict(a=1, b=2, c=3)" and it works everywhere without serialization/deserialization and manual type conversions. Python's type checkers can't provide any safety for you if you do that, but that's a deficiency in the language, not the concept.

> Classes aren't a great abstraction when enforcing program invariants like "this object must at least have fields a and b."

Can you elaborate on the functional difference between

- an enhanced dictionary where certain keys are guaranteed as part of the type, and

- a record type (class, struct, whatever) with named fields?