Skip to content

Commit

Permalink
fix bug in merge dicts: look for comma backwards
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli committed Jul 29, 2021
1 parent 3d20910 commit 7d2d6b3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 5 additions & 5 deletions pyupgrade/_plugins/pep584.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from pyupgrade._data import State
from pyupgrade._data import TokenFunc
from pyupgrade._token_helpers import find_closing_bracket
from pyupgrade._token_helpers import find_token


def _replace_dict_brackets(i: int, tokens: List[Token]) -> None:
Expand All @@ -39,8 +38,10 @@ def _remove_double_star(i: int, tokens: List[Token]) -> None:


def _replace_comma_with_pipe(i: int, tokens: List[Token]) -> None:
comma = find_token(tokens, i, ',')
tokens[comma] = Token('CODE', ' |')
j = i - 1
while not (tokens[j].name == 'OP' and tokens[j].src == ','):
j -= 1
tokens[j] = Token('CODE', ' |')


@register(ast.Dict)
Expand All @@ -54,8 +55,7 @@ def visit_Dict(

if all(key is None for key in node.keys) and len(node.values) > 1:
yield ast_to_offset(node), _replace_dict_brackets
arg_count = len(node.values)
for idx, arg in enumerate(node.values):
yield ast_to_offset(arg), _remove_double_star
if idx < arg_count - 1:
if idx > 0:
yield ast_to_offset(arg), _replace_comma_with_pipe
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,19 @@ def test_fix_pep584_noop(s, version):
id='Multiple lines, trailing comma',
),
pytest.param(
'x = {\n'
' **{a: a for a in range(3)},\n'
' **b,\n'
'}\n',
'x = (\n'
' {a: a for a in range(3)} |\n'
' b\n'
')\n',
id='Dict comprehension within merge of dicts',
),
),
)
def test_fix_pep584(s, expected):
Expand Down

0 comments on commit 7d2d6b3

Please sign in to comment.