Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unpickling in Python 3 #353

Merged
merged 1 commit into from
Oct 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions stripe/stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,28 @@ def __delitem__(self, k):
if hasattr(self, '_unsaved_values'):
self._unsaved_values.remove(k)

# Custom unpickling method that uses `update` to update the dictionary
# without calling __setitem__, which would fail if any value is an empty
# string
def __setstate__(self, state):
self.update(state)

# Custom pickling method to ensure the instance is pickled as a custom
# class and not as a dict, otherwise __setstate__ would not be called when
# unpickling.
def __reduce__(self):
reduce_value = (
type(self), # callable
( # args
self.get('id', None),
self.api_key,
self.stripe_version,
self.stripe_account
),
dict(self), # state
)
return reduce_value

@classmethod
def construct_from(cls, values, key, stripe_version=None,
stripe_account=None):
Expand Down
10 changes: 9 additions & 1 deletion stripe/test/resources/test_stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,14 @@ def test_pickling(self):
'foo', 'bar', myparam=5)

obj['object'] = 'boo'
obj.refresh_from({'fala': 'lalala'}, api_key='bar', partial=True)
obj.refresh_from(
{
'fala': 'lalala',
# ensures that empty strings are correctly unpickled in Py3
'emptystring': '',
},
api_key='bar', partial=True
)

self.assertEqual('lalala', obj.fala)

Expand All @@ -153,6 +160,7 @@ def test_pickling(self):
self.assertEqual('bar', newobj.api_key)
self.assertEqual('boo', newobj['object'])
self.assertEqual('lalala', newobj.fala)
self.assertEqual('', newobj.emptystring)

def test_deletion(self):
obj = stripe.stripe_object.StripeObject('id', 'key')
Expand Down