Skip to content

Conversation

@taleinat
Copy link
Contributor

@taleinat taleinat commented Sep 10, 2018

This is a backport of part of the implementation of bpo-30977 in PR #9106, which will not be backported in its entirety.

https://bugs.python.org/issue34621

@taleinat taleinat changed the title bpo-34621: fix UUID (un)pickling [3.7] bpo-34621: fix UUID (un)pickling Sep 10, 2018
@taleinat taleinat changed the title [3.7] bpo-34621: fix UUID (un)pickling [3.7] bpo-34621: fix uuid.UUID (un)pickling compatbility with older Python versions (<3.7) Sep 10, 2018
Lib/uuid.py Outdated
self.__dict__['is_safe'] = is_safe

def __getstate__(self):
d = {'int': self.int}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch! I've addressed this in the latest commit.

Note: I went with a more verbose spelling for overriding is_safe in __getstate__ which is IMO easier to read.

@taleinat taleinat merged commit d53f1ca into python:3.7 Sep 10, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants