Skip to content

Commit

Permalink
Remove extraneous parenthesis around keys in dict literals
Browse files Browse the repository at this point in the history
(Commit adapted from PR #171.)
  • Loading branch information
rvprasad authored and berkerpeksag committed Jan 1, 2025
1 parent 21cecd3 commit a99b237
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions astor/code_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,7 @@ def visit_Dict(self, node):
with self.delimit('{}'):
for idx, (key, value) in enumerate(zip(node.keys, node.values)):
if key:
set_precedence(Precedence.Comma, key)
set_precedence(Precedence.Comma, value)
self.write(', ' if idx else '',
key if key else '',
Expand Down
8 changes: 8 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ Bug fixes

.. _`PR 202`: https://github.com/berkerpeksag/astor/pull/202

* Remove extraneous parenthesis around keys in :class:`dict` literals. Astor
will now convert ``{(1): 2}`` and ``{(3 + 4): 5}`` to ``{1: 2}`` and
``{3 + 4: 5}`` respectively.

(Contributed by Venkatesh-Prasad Ranganath in `PR 171`_.)

.. _`PR 170`: https://github.com/berkerpeksag/astor/pull/171

0.8.1 - 2019-12-10
------------------

Expand Down
35 changes: 35 additions & 0 deletions tests/test_code_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,41 @@ def test_type_alias(self):
'''
self.assertSrcRoundtrips(source)

def test_do_not_add_excessive_parenthesis_in_keys_of_dict_literals(self):
source = 'spam = {(3):4}'
target = 'spam = {3: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {3:4}'
target = 'spam = {3: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {(3.0):4}'
target = 'spam = {3.0: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {3.0:4}'
target = 'spam = {3.0: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {(3+4):4}'
target = 'spam = {3 + 4: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {3+4:4}'
target = 'spam = {3 + 4: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

source = 'spam = {(3).foo:4}'
target = 'spam = {(3).foo: 4}'
astor.to_source(ast.parse(source))
self.assertAstEqualsSource(ast.parse(source), target)

if __name__ == '__main__':
unittest.main()

0 comments on commit a99b237

Please sign in to comment.