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
picklewith custom__getstate__and__setstate__methods for control. - Using libraries like
marshmalloworpydanticfor validation and serialization of complex data structures. - Serialization that preserves object references and cycles.
- Serialization to formats supporting extended types, such as
msgpackorprotobuf.
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.