From 9a331d606f3fd60cac19bfbfc3f98cbe8be2517d Mon Sep 17 00:00:00 2001 From: cobalt <61329810+RedGuy12@users.noreply.github.com> Date: Wed, 17 Jan 2024 13:04:15 -0600 Subject: [PATCH] fix: Don't allow unparenthesizing walruses (#4155) Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com> Signed-off-by: RedGuy12 --- CHANGES.md | 1 + src/black/linegen.py | 6 +++++- tests/data/cases/walrus_in_dict.py | 7 +++++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 tests/data/cases/walrus_in_dict.py diff --git a/CHANGES.md b/CHANGES.md index 8fb8677..2bd58ed 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,7 @@ - Address a missing case in the change to allow empty lines at the beginning of all blocks, except immediately before a docstring (#4130) - For stubs, fix logic to enforce empty line after nested classes with bodies (#4141) +- Fix crash when using a walrus in a dictionary (#4155) ### Configuration diff --git a/src/black/linegen.py b/src/black/linegen.py index 4d468ce..9a3eb0c 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -242,7 +242,11 @@ def visit_dictsetmaker(self, node: Node) -> Iterator[Line]: if i == 0: continue if node.children[i - 1].type == token.COLON: - if child.type == syms.atom and child.children[0].type == token.LPAR: + if ( + child.type == syms.atom + and child.children[0].type == token.LPAR + and not is_walrus_assignment(child) + ): if maybe_make_parens_invisible_in_atom( child, parent=node, diff --git a/tests/data/cases/walrus_in_dict.py b/tests/data/cases/walrus_in_dict.py new file mode 100644 index 0000000..c33eecd --- /dev/null +++ b/tests/data/cases/walrus_in_dict.py @@ -0,0 +1,7 @@ +# flags: --preview +{ + "is_update": (up := commit.hash in update_hashes) +} + +# output +{"is_update": (up := commit.hash in update_hashes)}