internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: psf/black

Issue:
Suggestion: Mention contextlib.ExitStack in "Use backslashes for with statements"?
**Is this related to a problem? Please describe.**

On [Black's future style doc](https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html#using-backslashes-for-with-statements) it talks about `black` handling a `with` with multiple context managers in a few ways (Python-version-dependent).

**Describe the solution you'd like**

Black should suggest to the user (in documentation only) that if they don't like Black's current or future behavior, that constructing a `contextlib.ExitStack` can help the issue while maintaining 95%-ish of the code readability and has minimal overhead.

As an example (feel free to steal), and using the existing code on that page

```python
with contextlib.ExitStack() as exit_stack:
    cm1 = exit_stack.enter_context(make_context_manager(1))
    cm2 = exit_stack.enter_context(make_context_manager(2))
    cm3 = exit_stack.enter_context(make_context_manager(3))
    cm4 = exit_stack.enter_context(make_context_manager(4))
    ...
```

**Describe alternatives you've considered**

N/A

**Additional context**

:heart:  black



Discussion:
Related: #2118 #1948
i would like to work on this.Im a beginner
Hi @Anika-Roy! Happy to see you'd like to contribute to Black! You should first take a look at https://black.readthedocs.io/en/latest/contributing/the_basics.html which provides an overview on contributing. 

I know our contributing documentation is lacking (matter of fact I'm currently working on rewriting them to be way better), so please don't worry about asking too many questions. If you use Discord, feel free to chat with us in the [#black-formatter channel on Python Discord](https://discord.gg/RtVdv86PrH)

---

For this issue specifically, since it only involves documentation, things are a lot simpler. Basically you should fork the repository, clone your fork, edit https://github.com/psf/black/blob/main/docs/the_black_code_style/future_style.md to include a few more paragraphs under the "Using backslashes for with statements" header according to the issue description. Actually, you could do all of this using the GitHub web editor instead, i.e. press `.`

Finally, make a PR with your changes to that one document and we'll start the review process. I'll share more on that once we get to that point :)

Good luck!

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -55,7 +55,7 @@ def make_pypi_svg(version: str) -> None:
 # -- General configuration ---------------------------------------------------
 
 # If your documentation needs a minimal Sphinx version, state it here.
-needs_sphinx = "3.0"
+needs_sphinx = "4.4"
 
 # Add any Sphinx extension module names here, as strings. They can be
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom


Test patch:
Repository: psf/black

Issue:
Fix start up code to also call freeze_support() on macOS when frozen so native macOS executables work
I broke the native macOS executables. [The build for 22.8.0 failed](https://github.com/psf/black/runs/8124297895?check_suite_focus=true) since the executable failed the basic sanity checks pre-upload
```
Usage: black_macos [OPTIONS] SRC ...
Try 'black_macos -h' for help.

Error: No such option: --multiprocessing-fork
Usage: black_macos [OPTIONS] SRC ...
Try 'black_macos -h' for help.

Usage: black_macos [OPTIONS] SRC ...
Try 'black_macos -h' for help.

Error: No such option: --multiprocessing-fork
Error: No such option: --multiprocessing-fork
error: cannot format src/black/__main__.py: A process in the process pool was terminated abruptly while the future was running or pending.
error: cannot format src/black/files.py: A process in the process pool was terminated abruptly while the future was running or pending.
```

When I first submitted https://github.com/psf/black/pull/3211 I checked how the stdlib guards the `freeze_support()` call and copied it:

- https://github.com/python/cpython/blob/2ecc195498f3b1256fabc2b66e0d8f6d671fa1d7/Lib/multiprocessing/context.py#L144-L150

So as far as I understand from reading the code, [macOS should not need `freeze_support()` to work with PyInstaller](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count:~:text=Calling%20freeze_support()%20has%20no%20effect%20when%20invoked%20on%20any%20operating%20system%20other%20than%20Windows), but apparently it does. Anyway let's fix this by including macOS in the OS check I guess.

https://github.com/psf/black/blob/2018e667a6a36ee3fbfa8041cd36512f92f60d49/src/black/__init__.py#L1377-L1384


Discussion:

Resolving patch:
diff --git a/src/black/__init__.py b/src/black/__init__.py
--- a/src/black/__init__.py
+++ b/src/black/__init__.py
@@ -1375,7 +1375,9 @@ def patch_click() -> None:
 
 
 def patched_main() -> None:
-    if sys.platform == "win32" and getattr(sys, "frozen", False):
+    # PyInstaller patches multiprocessing to need freeze_support() even in non-Windows
+    # environments so just assume we always need to call it if frozen.
+    if getattr(sys, "frozen", False):
         from multiprocessing import freeze_support
 
         freeze_support()


Test patch:
Repository: psf/black

Issue:
unreachable code in `parsing.py`
**Describe the bug**

unreachable code in `src\black\parsing.py:170`: 
`raise AssertionError("INTERNAL ERROR: Tried parsing unsupported Python version!")`

**Expected behavior**

not having unreachable code 😝 


Discussion:
@NNRepos, which versions of Python and black are you using? 
> @NNRepos, which versions of Python and black are you using?

this is true for any python version - i'm just doing static analysis of the `main` branch.
You're right, we can remove this line.
> You're right, we can remove this line.

great!
if you would like me to create a PR, please assign me to this issue 😄 

Resolving patch:
diff --git a/src/black/parsing.py b/src/black/parsing.py
--- a/src/black/parsing.py
+++ b/src/black/parsing.py
@@ -165,8 +165,6 @@ def parse_single_version(
         # comments separately.
         return ast3.parse(src, filename, feature_version=version[1])
 
-    raise AssertionError("INTERNAL ERROR: Tried parsing unsupported Python version!")
-
 
 def parse_ast(src: str) -> Union[ast.AST, ast3.AST]:
     # TODO: support Python 4+ ;)


Test patch:
Repository: psf/black

Issue:
black cli show loaded configuration.
**Is your feature request related to a problem? Please describe.**

Sometimes when dealing with multiple environment settings, IDEs, and pyproject.toml files etc. etc. is beneficial for a project team to have a confirmation about the actual applied black-settings ("line length") in the CI CD pipeline.

`black -v` will show a line like this:  `Using configuration from project root.`.
However, it doesn't tell us what the settings are, and it is not desirable to have all the other output of `-v` in all cases.

**Describe the solution you'd like**

Add CLI flag which will display the loaded config (could be similar to `git config`?)

**Describe alternatives you've considered**

Parsing the natural text "project root" is not desirable. Also it doesn't tell us what the resulting config is, including command line flags, or similar.

Explicit is better than implicit.

**Additional context**





Discussion:
I'm not sure this merits a new flag. Perhaps `-v` should simply print out the config settings?

Resolving patch:
diff --git a/src/black/__init__.py b/src/black/__init__.py
--- a/src/black/__init__.py
+++ b/src/black/__init__.py
@@ -511,6 +511,9 @@ def main(  # noqa: C901
                 out("Using configuration from project root.", fg="blue")
             else:
                 out(f"Using configuration in '{config}'.", fg="blue")
+            if ctx.default_map:
+                for param, value in ctx.default_map.items():
+                    out(f"{param}: {value}")
 
     error_msg = "Oh no! 💥 💔 💥"
     if (


Test patch:
Repository: psf/black

Issue:
Crash in preview style with assert + parenthesized string
```python
assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
    xxxxxxxxx
).xxxxxxxxxxxxxxxxxx(), (
    "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
```
Running `black --preview` on this file results in `error: cannot format xxxxxx.py: Unable to match a closing bracket to the following opening bracket: `.

This is a regression in 22.12.0. It bisects to #3370, cc @yilei.


Discussion:
Thanks for the cc, I'll take a look!

Resolving patch:
diff --git a/src/black/brackets.py b/src/black/brackets.py
--- a/src/black/brackets.py
+++ b/src/black/brackets.py
@@ -349,26 +349,23 @@ def get_leaves_inside_matching_brackets(leaves: Sequence[Leaf]) -> Set[LeafID]:
     Matching brackets are included.
     """
     try:
-        # Only track brackets from the first opening bracket to the last closing
-        # bracket.
+        # Start with the first opening bracket and ignore closing brackets before.
         start_index = next(
             i for i, l in enumerate(leaves) if l.type in OPENING_BRACKETS
         )
-        end_index = next(
-            len(leaves) - i
-            for i, l in enumerate(reversed(leaves))
-            if l.type in CLOSING_BRACKETS
-        )
     except StopIteration:
         return set()
+    bracket_stack = []
     ids = set()
-    depth = 0
-    for i in range(end_index, start_index - 1, -1):
+    for i in range(start_index, len(leaves)):
         leaf = leaves[i]
-        if leaf.type in CLOSING_BRACKETS:
-            depth += 1
-        if depth > 0:
-            ids.add(id(leaf))
         if leaf.type in OPENING_BRACKETS:
-            depth -= 1
+            bracket_stack.append((BRACKET[leaf.type], i))
+        if leaf.type in CLOSING_BRACKETS:
+            if bracket_stack and leaf.type == bracket_stack[-1][0]:
+                _, start = bracket_stack.pop()
+                for j in range(start, i + 1):
+                    ids.add(id(leaves[j]))
+            else:
+                break
     return ids


Test patch:
diff --git a/tests/data/preview/trailing_commas_in_leading_parts.py b/tests/data/preview/trailing_commas_in_leading_parts.py
--- a/tests/data/preview/trailing_commas_in_leading_parts.py
+++ b/tests/data/preview/trailing_commas_in_leading_parts.py
@@ -25,6 +25,13 @@ def refresh_token(self, device_family, refresh_token, api_key):
     == long_module.long_class.long_func()["some_key"].another_func(arg1)
 )
 
+# Regression test for https://github.com/psf/black/issues/3414.
+assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
+    xxxxxxxxx
+).xxxxxxxxxxxxxxxxxx(), (
+    "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+)
+
 
 # output
 
@@ -72,3 +79,10 @@ def refresh_token(self, device_family, refresh_token, api_key):
     long_module.long_class.long_func().another_func()
     == long_module.long_class.long_func()["some_key"].another_func(arg1)
 )
+
+# Regression test for https://github.com/psf/black/issues/3414.
+assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
+    xxxxxxxxx
+).xxxxxxxxxxxxxxxxxx(), (
+    "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+)
Repository: psf/black

Issue:
EncodingWarning in pgen
Relating to #3658, if PYTHONWARNDEFAULTENCODING is set, this library raises a warning at:

https://github.com/psf/black/blob/2fd9d8b339e1e2e1b93956c6d68b2b358b3fc29d/src/blib2to3/pgen2/pgen.py#L42




Discussion:

Resolving patch:
diff --git a/src/blib2to3/pgen2/pgen.py b/src/blib2to3/pgen2/pgen.py
--- a/src/blib2to3/pgen2/pgen.py
+++ b/src/blib2to3/pgen2/pgen.py
@@ -30,7 +30,6 @@ class PgenGrammar(grammar.Grammar):
 
 
 class ParserGenerator(object):
-
     filename: Path
     stream: IO[Text]
     generator: Iterator[GoodTokenInfo]
@@ -39,7 +38,7 @@ class ParserGenerator(object):
     def __init__(self, filename: Path, stream: Optional[IO[Text]] = None) -> None:
         close_stream = None
         if stream is None:
-            stream = open(filename)
+            stream = open(filename, encoding="utf-8")
             close_stream = stream.close
         self.filename = filename
         self.stream = stream


Test patch:
Repository: psf/black

Issue:
Black adds unexpected trailing comma in return type wrapped in parenthesis
Code before:

```python
def asdf_asdf_asdf_asdf_asdf() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None:
    pass
```

Black formatted to:

```python
def asdf_asdf_asdf_asdf_asdf() -> (
    my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None,
):
    pass
```

The trailing comma is incorrect, see [playground](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADcAH1dAD2IimZxl1N_WlbvK5V8JNI78iDZsHigDVyjE4tQWha-38JzxuA6NBKsp2kEtoZDrhhVy-9l-YBts85jfOzh4b304nwAUyJ1g-2SirojMNIYrAMgd5VvDgyl5O8GOXrT088SOzYVPBPYBGEPOKU2W0UtnaTHwP-n62bl9QsAAAAAAM5q0vB1zdcRAAGZAd0BAACVsaARscRn-wIAAAAABFla).


Discussion:

Resolving patch:
diff --git a/src/black/linegen.py b/src/black/linegen.py
--- a/src/black/linegen.py
+++ b/src/black/linegen.py
@@ -918,6 +918,13 @@ def bracket_split_build_line(
                     )
                     if isinstance(node, Node) and isinstance(node.prev_sibling, Leaf)
                 )
+                # Except the false negatives above for PEP 604 unions where we
+                # can't add the comma.
+                and not (
+                    leaves[0].parent
+                    and leaves[0].parent.next_sibling
+                    and leaves[0].parent.next_sibling.type == token.VBAR
+                )
             )
 
             if original.is_import or no_commas:


Test patch:
diff --git a/tests/data/simple_cases/pep_604.py b/tests/data/simple_cases/pep_604.py
new file mode 100644
--- /dev/null
+++ b/tests/data/simple_cases/pep_604.py
@@ -0,0 +1,25 @@
+def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None:
+    pass
+
+
+def some_very_long_name_function() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | my_module.EvenMoreType | None:
+    pass
+
+
+# output
+
+
+def some_very_long_name_function() -> (
+    my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None
+):
+    pass
+
+
+def some_very_long_name_function() -> (
+    my_module.Asdf
+    | my_module.AnotherType
+    | my_module.YetAnotherType
+    | my_module.EvenMoreType
+    | None
+):
+    pass
Repository: psf/black

Issue:
Allow specifying `--workers` via environment variable
**Is your feature request related to a problem? Please describe.**

I ran into https://github.com/psf/black/issues/2513 in my CI system

While I can hardcode `--workers` into my invocations of black (in this case, via pre-commit), it's a little unnatural, since the number of cores differs between CI workers and say locally. E.g., I can hardcode the minimum of them, but then we leave some perf on the table.

**Describe the solution you'd like**

I'd like to specify it by environment variable, say `BLACK_NUM_WORKERS`. This isn't unprecedented, e.g. `BLACK_CACHE_DIR` exists. This does increase configuration complexity a little.

**Describe alternatives you've considered**

Just hardcoding `--workers`. It's not the biggest deal.


Discussion:

Resolving patch:
diff --git a/src/black/__init__.py b/src/black/__init__.py
--- a/src/black/__init__.py
+++ b/src/black/__init__.py
@@ -373,7 +373,10 @@ def validate_regex(
     "--workers",
     type=click.IntRange(min=1),
     default=None,
-    help="Number of parallel workers [default: number of CPUs in the system]",
+    help=(
+        "Number of parallel workers [default: BLACK_NUM_WORKERS environment variable "
+        "or number of CPUs in the system]"
+    ),
 )
 @click.option(
     "-q",
diff --git a/src/black/concurrency.py b/src/black/concurrency.py
--- a/src/black/concurrency.py
+++ b/src/black/concurrency.py
@@ -80,7 +80,8 @@ def reformat_many(
 
     executor: Executor
     if workers is None:
-        workers = os.cpu_count() or 1
+        workers = int(os.environ.get("BLACK_NUM_WORKERS", 0))
+        workers = workers or os.cpu_count() or 1
     if sys.platform == "win32":
         # Work around https://bugs.python.org/issue26903
         workers = min(workers, 60)


Test patch:
Repository: psf/black

Issue:
comment next to string wrapped in parentheses in list removed in preview mode
[playground](https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADmAGddAD2IimZxl1N_Wk2dwftOJ50SbV6YWHXSlk0zMjeaZSSdUyjbepJazuUgWDu9lpp1YM-ezqWPKfSzFYI-BdUysyJBqFNFtl1R7h2T0yqLVfjIVWrxRgqamVUQA6Io-0--gxoknMQQNPcAAJft286GImO8AAGDAecBAACtiHssscRn-wIAAAAABFla)
# before
```py
[
    (
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    ),
]
```
# after
```py
["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]

```


Discussion:

Resolving patch:
diff --git a/src/black/trans.py b/src/black/trans.py
--- a/src/black/trans.py
+++ b/src/black/trans.py
@@ -942,6 +942,9 @@ def _transform_to_new_line(
                 LL[lpar_or_rpar_idx].remove()  # Remove lpar.
                 replace_child(LL[idx], string_leaf)
                 new_line.append(string_leaf)
+                # replace comments
+                old_comments = new_line.comments.pop(id(LL[idx]), [])
+                new_line.comments.setdefault(id(string_leaf), []).extend(old_comments)
             else:
                 LL[lpar_or_rpar_idx].remove()  # This is a rpar.
 


Test patch:
diff --git a/tests/data/preview/comments7.py b/tests/data/preview/comments7.py
--- a/tests/data/preview/comments7.py
+++ b/tests/data/preview/comments7.py
@@ -131,6 +131,18 @@ def test_fails_invalid_post_data(
 
 square = Square(4) # type: Optional[Square]
 
+# Regression test for https://github.com/psf/black/issues/3756.
+[
+    (
+        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+    ),
+]
+[
+    (  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+    ),
+]
+
 # output
 
 from .config import (
@@ -282,3 +294,15 @@ def test_fails_invalid_post_data(
 
 
 square = Square(4)  # type: Optional[Square]
+
+# Regression test for https://github.com/psf/black/issues/3756.
+[
+    (  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+    ),
+]
+[
+    (  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"  # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+    ),
+]
Repository: psf/black

Issue:
Internal error: AST change with bytes docstring
Black reformats the contents of triple quoted byte strings in docstring position, even though those are not docstrings, causing a crash due to AST changes:

```python
def f():
    b""" a"""
```

```diff
INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_rb9415ox.log

--- src
+++ dst
@@ -18,11 +18,11 @@
           value=
             Constant(
               kind=
                 None,  # NoneType
               value=
-                b' a',  # bytes
+                b'a',  # bytes
             )  # /Constant
         )  # /Expr
       decorator_list=
       name=
         'f',  # str
```

```console
$ python3.12
Python 3.12.0 (main, Oct  6 2023, 17:57:44) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     b""" a"""
... 
>>> print(str(f.__doc__))
None
```

Surprisingly, the empty line rules for class level docstrings look already correct.

Confirmed to occur on 23.10.1 and main (f7cbe4a) with the playground.


Discussion:

Resolving patch:
diff --git a/src/black/nodes.py b/src/black/nodes.py
--- a/src/black/nodes.py
+++ b/src/black/nodes.py
@@ -14,7 +14,7 @@
 
 from black.cache import CACHE_DIR
 from black.mode import Mode, Preview
-from black.strings import has_triple_quotes
+from black.strings import get_string_prefix, has_triple_quotes
 from blib2to3 import pygram
 from blib2to3.pgen2 import token
 from blib2to3.pytree import NL, Leaf, Node, type_repr
@@ -525,6 +525,13 @@ def is_arith_like(node: LN) -> bool:
 
 
 def is_docstring(leaf: Leaf) -> bool:
+    if leaf.type != token.STRING:
+        return False
+
+    prefix = get_string_prefix(leaf.value)
+    if "b" in prefix or "B" in prefix:
+        return False
+
     if prev_siblings_are(
         leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
     ):


Test patch:
diff --git a/tests/data/cases/bytes_docstring.py b/tests/data/cases/bytes_docstring.py
new file mode 100644
--- /dev/null
+++ b/tests/data/cases/bytes_docstring.py
@@ -0,0 +1,34 @@
+def bitey():
+    b" not a docstring"
+
+def bitey2():
+    b' also not a docstring'
+
+def triple_quoted_bytes():
+    b""" not a docstring"""
+
+def triple_quoted_bytes2():
+    b''' also not a docstring'''
+
+def capitalized_bytes():
+    B" NOT A DOCSTRING"
+
+# output
+def bitey():
+    b" not a docstring"
+
+
+def bitey2():
+    b" also not a docstring"
+
+
+def triple_quoted_bytes():
+    b""" not a docstring"""
+
+
+def triple_quoted_bytes2():
+    b""" also not a docstring"""
+
+
+def capitalized_bytes():
+    b" NOT A DOCSTRING"
\ No newline at end of file
diff --git a/tests/data/raw_docstring.py b/tests/data/cases/raw_docstring.py
similarity index 100%
rename from tests/data/raw_docstring.py
rename to tests/data/cases/raw_docstring.py
Repository: psf/black

Issue:
Avoid removing whitespace for parenthesized walrus in subscripts
**Describe the bug**

Related to the new [`walrus_subscript`](https://github.com/psf/black/pull/3823) preview style and has previously been mentioned in [this comment](https://github.com/psf/black/pull/3823#issuecomment-1656883294)

Black removes whitespace around parenthesized walrus operators but preserves them for other binary operations:

```python
x[(a + 4) :]
x[(a := 4):]
```

I would expect that the walrus operator gets formatted the same as any other binary operator:

```python
x[(a := 4) :]
```


**To Reproduce**

See [Playground](https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AChAGhdAD2IimZxl1N_WmyxQ1GdQjZJ-UrtnkUC9HhNd4a2tNtFILOWrdvGricHZE-n29mbSRpvTO-8jSUqWnUW6pkgfj_XJzMl2ywm3QXwbYWMn5Ez-EO1iE4wEv-NmSwVw_NqslDlLQF4NJ0AAAboJbMfO3D7AAGEAaIBAAAaELSdscRn-wIAAAAABFla)



Discussion:
Agree we should change this.

Resolving patch:
diff --git a/src/black/lines.py b/src/black/lines.py
--- a/src/black/lines.py
+++ b/src/black/lines.py
@@ -446,8 +446,15 @@ def is_complex_subscript(self, leaf: Leaf) -> bool:
 
             if subscript_start.type == syms.subscriptlist:
                 subscript_start = child_towards(subscript_start, leaf)
+
+        # When this is moved out of preview, add syms.namedexpr_test directly to
+        # TEST_DESCENDANTS in nodes.py
+        if Preview.walrus_subscript in self.mode:
+            test_decendants = TEST_DESCENDANTS | {syms.namedexpr_test}
+        else:
+            test_decendants = TEST_DESCENDANTS
         return subscript_start is not None and any(
-            n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
+            n.type in test_decendants for n in subscript_start.pre_order()
         )
 
     def enumerate_with_length(


Test patch:
diff --git a/tests/data/cases/preview_pep_572.py b/tests/data/cases/preview_pep_572.py
--- a/tests/data/cases/preview_pep_572.py
+++ b/tests/data/cases/preview_pep_572.py
@@ -3,5 +3,5 @@
 x[:(a:=0)]
 
 # output
-x[(a := 0):]
-x[:(a := 0)]
+x[(a := 0) :]
+x[: (a := 0)]