Sobes.tech
Junior — Middle

Have you worked with advanced or complex data serialization mechanisms?

sobes.tech AI

Answer from AI

Yes, Python has advanced serialization mechanisms beyond the standard pickle and json.

For example:

  • Serialization of complex objects using pickle with custom __getstate__ and __setstate__ methods for control.
  • Using libraries like marshmallow or pydantic for validation and serialization of complex data structures.
  • Serialization that preserves object references and cycles.
  • Serialization to formats supporting extended types, such as msgpack or protobuf.

Example of custom serialization with pickle:

import pickle

class MyClass:
    def __init__(self, data):
        self.data = data
    def __getstate__(self):
        state = self.__dict__.copy()
        # modify state before serialization if needed
        return state
    def __setstate__(self, state):
        # restore object
        self.__dict__.update(state)

obj = MyClass([1, 2, 3])
data = pickle.dumps(obj)
new_obj = pickle.loads(data)

Thus, you can flexibly control the serialization and deserialization process.