Skip to content

Commit d66dd5c

Browse files
committed
Issue #26489: Add dictionary unpacking support to Tools/parser/unparse.py
Patch by Guo Ci Teo.
1 parent e88dd1c commit d66dd5c

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

Lib/test/test_tools/test_unparse.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,11 @@ def test_with_as(self):
250250
def test_with_two_items(self):
251251
self.check_roundtrip(with_two_items)
252252

253+
def test_dict_unpacking_in_dict(self):
254+
# See issue 26489
255+
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
256+
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")
257+
253258

254259
class DirectoryTestCase(ASTTestCase):
255260
"""Test roundtrip behaviour on all files in Lib and Lib/test."""

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,9 @@ Windows
328328
Tools/Demos
329329
-----------
330330

331+
- Issue #26489: Add dictionary unpacking support to Tools/parser/unparse.py.
332+
Patch by Guo Ci Teo.
333+
331334
- Issue #26316: Fix variable name typo in Argument Clinic.
332335

333336

Tools/parser/unparse.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,12 +393,21 @@ def _Set(self, t):
393393

394394
def _Dict(self, t):
395395
self.write("{")
396-
def write_pair(pair):
397-
(k, v) = pair
396+
def write_key_value_pair(k, v):
398397
self.dispatch(k)
399398
self.write(": ")
400399
self.dispatch(v)
401-
interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))
400+
401+
def write_item(item):
402+
k, v = item
403+
if k is None:
404+
# for dictionary unpacking operator in dicts {**{'y': 2}}
405+
# see PEP 448 for details
406+
self.write("**")
407+
self.dispatch(v)
408+
else:
409+
write_key_value_pair(k, v)
410+
interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values))
402411
self.write("}")
403412

404413
def _Tuple(self, t):

0 commit comments

Comments
 (0)