[3.7] bpo-34621: fix uuid.UUID (un)pickling compatbility with older Python versions (<3.7) by taleinat · Pull Request #9133 · python/cpython (original) (raw)
In Python 3.6 and older the UUID object can have additional attributes, which will be preserved with pickling. I don't know whether anybody uses this, and don't think we should add tests for this, but it is better to avoid breaking in maintained release without need. I would write the following code:
def __getstate__(self):
state = self.__dict__
if self.is_safe != SafeUUID.unknown:
# is_safe is a SafeUUID instance. Return just its value, so that
# it can be un-pickled in older Python versions without SafeUUID.
state = {**state, 'is_safe': self.is_safe.value}
return state
def __setstate__(self, state):
self.__dict__.update(state)
# is_safe was added in 3.7; it is also omitted when it is "unknown"
self.__dict__['is_safe'] = (SafeUUID(state['is_safe'])
if 'is_safe' in state else SafeUUID.unknown)