Skip to content

Commit 78e3d0a

Browse files
committed
Fix issue where StripeObjects in lists would not be converted to dicts
1 parent dc8fd30 commit 78e3d0a

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

stripe/stripe_object.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -278,11 +278,20 @@ def to_dict(self):
278278
return dict(self)
279279

280280
def to_dict_recursive(self):
281-
d = dict(self)
282-
for k, v in six.iteritems(d):
283-
if isinstance(v, StripeObject):
284-
d[k] = v.to_dict_recursive()
285-
return d
281+
def maybe_to_dict_recursive(value):
282+
if value is None:
283+
return None
284+
elif isinstance(value, StripeObject):
285+
return value.to_dict_recursive()
286+
else:
287+
return value
288+
289+
return {
290+
key: list(map(maybe_to_dict_recursive, value))
291+
if isinstance(value, list)
292+
else maybe_to_dict_recursive(value)
293+
for key, value in six.iteritems(dict(self))
294+
}
286295

287296
@property
288297
def stripe_id(self):

tests/test_stripe_object.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,30 @@ def test_deepcopy(self):
291291
# Verify that we're actually deep copying nested values.
292292
assert id(nested) != id(copied.nested)
293293

294+
def test_to_dict_recursive(self):
295+
foo = stripe.stripe_object.StripeObject.construct_from(
296+
{"value": "foo"}, "mykey"
297+
)
298+
bar = stripe.stripe_object.StripeObject.construct_from(
299+
{"value": "bar"}, "mykey"
300+
)
301+
obj = stripe.stripe_object.StripeObject.construct_from(
302+
{"empty": "", "value": "foobar", "nested": [foo, bar]}, "mykey"
303+
)
304+
305+
d = obj.to_dict_recursive()
306+
assert d == {
307+
"empty": "",
308+
"value": "foobar",
309+
"nested": [{"value": "foo"}, {"value": "bar"}],
310+
}
311+
assert not isinstance(
312+
d["nested"][0], stripe.stripe_object.StripeObject
313+
)
314+
assert not isinstance(
315+
d["nested"][1], stripe.stripe_object.StripeObject
316+
)
317+
294318
def test_serialize_empty_string_unsets(self):
295319
class SerializeToEmptyString(stripe.stripe_object.StripeObject):
296320
def serialize(self, previous):

0 commit comments

Comments
 (0)