#black-formatter

1 messages · Page 7 of 1

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the style change

Black treats long lines that can be broken into two differently from those that can be broken into three or more. It seems to me that, unfortunately, in the first case it does it quite poorly.

Examples in the current Black style

match "some very long string to match".split():
    case ["string", "some", "very", "long", "to", "match"] | [
        "very",
        "some",
        "long",
        "string",
        "to",
        ...
flat krakenBOT
#

Fixes #2863

This is pretty desirable in a monorepo situation where you have configuration in the root since it will mean you don't have to reconfigure every project.

The good news for backward compatibility is that find_project_root continues to stop at any git or hg root, so in all cases repo root coincides with a pyproject.toml missing tool.black, we'll continue to have the project root as before and end up using default config (i.e. we're unlikely to randomly start using the user c...

flat krakenBOT
#

Describe the bug

black incorrectly ignores a file in the current folder

To Reproduce

(.venv) C:\>dir

12/21/2023  10:19 AM         Code [C:\ws]
...
02/02/2024  08:33 AM              ws

(.venv) C:\>cd Code

(.venv) C:\Code>mkdir Bug

(.venv) C:\Code>cd Bug

(.venv) C:\Code\Bug>git init
Initialized empty Git repository in C:/ws/Bug/.git/

(.venv) C:\Code\Bug>echo 1 > bug.py

(.venv) C:\Code\Bug>black --verbose bug.py
Identified `C:\ws\Bug` as project roo...
timber dock
#

Quick question about Black. Can it be used to format a block of code in a string variable? What I am seein in examples is formatting a file that is already written to a file. Thanks.

flat krakenBOT
flat krakenBOT
#

Describe the bug

I want to use blackd together with PyCharm (standalone or via Gateway). This has worked fine all the time, for a long time, many different versions, many different environments. Now suddenly, I get a strange error in PyCharm:

With PyCharm (via Gateway), when I try to check the connection, I get:

Cannot connect to blackd:  Unsupported or unrecognized SSL message

When I run blackd directly in the shell, I see this error Invalid method encountered...

hushed marsh
#

hey

#

i need helpo dm me

grand cipher
#

I just wanted to say: Great work on recent black releases! The preview style fixes 80% of my gripes and niggles with the black format, and even a couple I didn't know I had! Keep up the good work, and thanks so much.


P.S. Only if you're curious: The last 20% involves the way black adds/removes blank lines from my code, and changing the visual meaning of the code: https://github.com/psf/black/issues/2543

flat krakenBOT
#

We merged string processing in May 2020 (#1132), almost four years ago. A few months later, I put the feature behind a flag because there were too many related bugs (#1609). Four years later, we're still in basically the same state: most of the open issues in https://github.com/psf/black/labels/C%3A preview style are about string processing.

I'm also increasingly convinced that string_processing's core feature, splitting up long strings, would be exceedingly controversial if we ever di...

flat krakenBOT
flat krakenBOT
elder tusk
#

Black doesn't collect telemetry (and never will), so we don't know. We test all changes against a corpus of open source projects. Preview users often give feedback on style changes. If you have feedback, I'd encourage you to open an issue. This is a project that runs on volunteer effort.

flat krakenBOT
flat krakenBOT
#

The issue

The newest black folds the ellipsis (...) to the previous line. This change may violate flake8 E701 rule if ellipsis is used for defining a class.

To Reproduce the issue

The following codes will not raise flake8 errors:

def test():
    ...


class test2:
    ...

After running black, the results are

def test(): ...


class test2: ...  # E701: Multiple statements on one line (colon)

Note that th...

flat krakenBOT
#

Description

A follow up to #4024 but for if guards in case statements. I noticed this when #4024 was made stable, and noticed I had some code that had extra parens around the if guard.

There might be some edge cases I am not thinking of, but all tests are passing. I put these new changes under the remove_redundant_guard_parens preview name.

Checklist

  • [x] Add an entry in CHANGES.md if necessary?
  • [x] Add / update tests if necessary?
  • [x] Add new / update out...
flat krakenBOT
#

Description

Currently find_project_root() resolves symlinks, but get_sources() doesn't, so trying to format a file that contains symlinks will fail:

$ python -m black --check /home/nfvs/code/black/src/black/files.py
No Python files are present to be formatted. Nothing to do 😴

This commit changes methods used in get_sources() to, like find_project_root(), use Path.resolve() instead of Path.absolute(), which will follow symlinks.

Also fixes: https://gith...

flat krakenBOT
#

Describe the bug

In Python 3.12, black formatter may change the content of string in nested f-strings

To Reproduce

For example, take this code:

def test(parts: list[str]):
    print(f"{"-".join(parts)}")

And run it with these arguments:

$ black test.py --target-version=py312 

The resulting error is:

contents changed to:

def test(parts: list[str]):
    print(f"{" - ".join(parts)}")

Expected behavior

cont...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

While using black on Windows cmd and VSCode, the slice of a longstring will cause line breaks.
For example, In:

s = """
"""[1:]
li = """
""".splitlines()[1:-1]

Out:

s = """
"""[
    1:
]
li = """
""".splitlines()[
    1:-1
]

I don't know if it supposes to be like this.

The command I used is:

C:\Windows\system32>pip install -U black
C:\Windows\system32>python -m black file.py

and Hotkey Alt + Shift + F in VSCode.

**Envi...

glacial swan
#

Okay how would I use a specific python version with this?:

name: CI

on: [push, pull_request]

jobs:
  black:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Run linter
        uses: psf/black@stable
        with:
          options: "--line-length 120"
          src: "."

      - name: Commit & push changes (main only)
        if: github.event_name == 'push' && github.ref_name == 'master'
        continue-on-error: true
        run: |
          git config user.name "github-actions"
          git config user.email "github-actions@example.com"
          git add -A
          git commit -m "[ci] Autoformat with black"
          git push

      - name: Fail job if changes were made (PR only)
        if: github.event_name == 'pull_request'
        run: git diff-index --quiet HEAD -- || (git diff && exit 1)
#

cause it seems to use a different python version than me

#

and it reformats what i have already formatted

#

the one I am trying to use it with is Python3.10

elder tusk
#

set target version in your pyproject.toml?

glacial swan
#
[tool.black]
line-length = 120
#

then what?

silent knoll
#

is https://black.vercel.app currently maintained at all? there's some things that should be added to it, specifically a way to toggle --unstable

Playground for Black, the uncompromising Python code formatter.

dense jungle
silent knoll
#

noted

flat krakenBOT
#

Describe the bug

black crashes when encountering a type: ignore comment on a line-broken ==, where the == is the first line.

To Reproduce

For example, take this code:

z = (
    x == # type: ignore[foo]
    y # type: ignore[foo]
  ) #  error: cannot format -: 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: /var/folders/0m/7yv6pgt57vzdqf...
glacial swan
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

This relates to #4015, #4161 and the behaviour of os.getcwd()

Black is a big user of pathlib and as such loves doing .resolve(), since for a long time it was the only good way of getting an absolute path in pathlib. However, this has two problems:

The first minor problem is performance, e.g. in #3751 I (safely) got rid of a bunch of .resolve() which made Black 40% faster on cached runs.

The second more important problem is that always resolving symlinks results in unintuitive exc...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Running Black with both --quiet and --check on a non-valid file leads to an exit status of 1 (correct) but no error being printed (unexpected).

Easy to reproduce, e.g. with

def foo(): print("bar")
foo()

python -m black --quiet --check test.py exits with status 1 but does not print anything.

Reproduced with Black 23.12.1 and 24.1.1.

For --quiet, help output states:

Stop emitting all non-critical output. Error messages will still be emitted

This i...

flat krakenBOT
flat krakenBOT
#

I'd say that this is somewhere between a bug report and a feature request. Consider the following piece of code:

def really_really_really_long_function_name(with_long_arguments, that_would_fit_on, one_line):
    another_really_really_long_function_name(with_long_arguments, that_would_fit_on, one_line)

    a_really_really_really_really_long_list = [with_long_arguments, that_would_fit_on, one_line]
    
    a_really_really_really_really_long_set = {with_long_arguments, that_...
flat krakenBOT
#

Describe the bug

Lines do not get cut up after line-length.

According to @JelleZijlstra in issue #1802 the following should work but it does not:

To Reproduce

For example, take this code:

black -v --preview -c 'long = "This is a long line that is longer than 88 characters. I expect Black to shorten this line length."'
Using configuration from project root.
line_length: 88
preview: True
target_version: ['py311']
long = "This is a long line that is longe...
#
% cat parens.py 
(x)
(1)
(yield 42)
([])
({})
(a + b)
% black --unstable --diff parens.py
All done! ✨ 🍰 ✨
1 file would be left unchanged.

I think all of these parentheses should be removed.

We should keep parentheses around a top-level expression (ast.Expr) only if:

  • There is a comment associated with the parentheses
  • It's a ternary split into multiple lines
  • Possibly other cases I haven't thought of
flat krakenBOT
flat krakenBOT
#

Describe the bug

I found this bug while trying to run black on it's own source code.

The file generate_schema.py in the scripts folder failed to get parsed properly.

To Reproduce

This is the function that causes the issue,

def generate_schema_from_click(
    cmd: click.Command,
) -> dict[str, Any]:
    result: dict[str, dict[str, Any]] = {}
    for param in cmd.params:
        if not isinstance(param, click.Option) or param.is_eager:
            c...
flat krakenBOT
#

I'm using Black with VSCode. Both are up to date.

black, 24.2.0 (compiled: yes)
Python (CPython) 3.11.5

I have a symbolic folder that I added to my workspace. It used to format properly when I made changes and saved the file. However the Black formatter output window now gave the following errors:

2024-02-15 07:57:38.915 [info] [Trace - 7:57:38 AM] Sending notification 'textDocument/didChange'.
2024-02-15 07:57:43.962 [info] [Trace - 7:57:43 AM] Sending request 'tex...
flat krakenBOT
#

Describe the bug

Black doesn't count line length correctly in case of khmer characters. They fit screen-wise (kind of) but character length goes beyond limit.

To Reproduce

For example, take this code:

@pytest.mark.parametrize(
    "text, expected_language",
    [
        (
            (
                "សម្រស់ទាវ២០២២ មិនធម្មតា ឥឡូវកំពុងរកតួ នេនទុំ និងពេជ្រ"
                " ប្រញាប់ឡើងទាន់គេមានបញ្ហាត្រូវថតឡើងវិញ "
            ),
            "km",
      ...
flat krakenBOT
#

Description

This closes #4227

black was previously not printing any information when called with the --quiet and --check flags.

the related issue makes a valid point that black should stay quiet on successful runs and notify the user when changes are found.

I've omitted part of the output in an attempt to keep the output still quiet, but I can add it in if desired.

For example, when called without the --quiet flag:

would reformat ../test_black/test.py

...
flat krakenBOT
#

Is this related to a problem? Please describe.

There has been some back-and-forth regarding empty line after code block open recently. The latest behavior is to keep zero empty line if that is the case in the original input, or one empty line if the original input has more than one empty lines.

However, this behavior is NOT reflected in the [documented code style on empty lines](https://github.com/psf/black/blob/stable/docs/the_black_code_...

flat krakenBOT
flat krakenBOT
#

Description

When using brackets to group mathematical operations to establish the precedence and order of such operations, black removes the brackets and breaks the grouping of mathematical operation. The example in my case is in the attached screenshot.

To Reproduce

from decimal import Decimal


m = Decimal("1.25")
if True:
    m *= (1 - Decimal("1.95"))
    print(m)
else:
    print(m)

And run it with these arguments:

black -t py39 --line-length 99...
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

IPython expands ! to %system, see
https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-system
These are also valid in notebooks.

Describe the solution you'd like

Python does not have a '!' operator. So somehow IPython is parsing it, maybe the parsing code can be modified to detect it, in which case the whole cell would not formatted, as it is done for cell magics currently.

**Describe altern...

flat krakenBOT
#

Description

Don't clobber result of best_effort_relative_path. Some how this was missed during but we had:
root_relative_path = best_effort_relative_path(path, root).as_posix()
root_relative_path = "/" + root_relative_path

Obviously not what was intended in PR #4222

Checklist - did you ...

  • [*] Add an entry in CHANGES.md if necessary?
  • [*] Add / update tests if necessary?
  • [*] Add new / update outdated documentation?
flat krakenBOT
#

While attempting to write a HTTP client for blackd to integrate into Sublime Text editor, I realized that blackd currently does not support the following black.FileMode options:

is_ipynb
python_cell_magics
unstable
enabled_features

The most important (for me at least) appears to be enabled_features, since it implies a list of further sub-options which are not configurable at the moment.

flat krakenBOT
#

When chaining multiple methods together as such:

def f():
    data = item_preprocessor \
        .handle_missing_values(strategy="mean") \
        .multilabel_binarize(["tags"]) \
        .normalize(["price"], methods=["z-score"]) \
        .onehot_encode(categorical_columns=["category"]) \
        .select_features(regex="^ftr.*", columns=["price"])

Black formats as such:

def f():
    data = (
        item_preprocessor.handle_missing_values(...
flat krakenBOT
#

Description

This branch should fix https://github.com/psf/black/issues/2547

It is sometimes the case that Vim was built with a different Python version than the one used by Black.
One such scenario is when the black virtualenv was created by an older version of Vim and then the system was upgraded in place.
Another scenario is when g:black_use_virtualenv is disabled and the manually created environment in g:black_virtualenv uses a different Python version. Right now Ubuntu...

indigo dagger
#

What's the progress on making a new stable release for VSCode extension with 23.11+?

dense jungle
azure plank
flat krakenBOT
#

Describe the bug

The following code failed with a Cannot parse message.

a = f"{10 * ["a"]}"

To Reproduce

Take the above code, save to a file and run

$ black 

The resulting error is:

error: cannot format /Users/zhongxia.zhou/REMHealth/projects/dataingest/src/dataingest/plans/test.py: Cannot parse: 1:14: a = f"{10 * ["a"]}"

Expected behavior

This is valid Python code and so black should be able to format it.

Environment

...

dense jungle
#

we should pin the PEP 701 issue

woeful tapir
#

how do i get black formatter to stop putting this on one line?

slow ibex
#
  • add + in between
  • add comment at the end of each line
#

or this ```py
''.join([
'a',
'b',
'c', # note the trailing comma
])

#

and you always can use # fmt: off/# fmt: on

flat krakenBOT
#

Describe the bug

When an assert statement has a multi-line string, the condition is split across 3 lines for no reason.

To Reproduce

For example, take this code:

assert some_var == expected_result, f"""
expected: {expected_result}
actual: {some_var}"""

And run it with these arguments:

$ black file.py

The resulting output is:

assert (
    some_var == expected_result
), f"""
expected: {expected_result}
actual: {some_var}...
flat krakenBOT
#

Description

Resolves #4220. Black moved the + at the end of the line to the start of the next line, then unintentionally moved any comments as well. This could cause type: ignore comments to be merged. To fix this, I stopped Black from moving any comments with the delimiter. It only crashed with type: ignore comments, but I think it makes sense to keep all comments on their original line instead of following the delimiter. This does not break the stability policy since pre-Blackene...

earnest swift
#

is '# in:' the Black formatter style?

astral brook
#

Hi I started using the Fleet editor by JetBrains and I don't know how to have it use black as the formatter and have it reformat on save. I'm using poetry as my package manager and I have a .editorconfig file in my projects directory per their docs on formatting rules but fleet still isn't formatting on save nor when I use the command to reformat code.

.editorconfig As per black documentation

[*.py]
profile = black
flat krakenBOT
flat krakenBOT
#

Describe the bug

When Black is applied to a folder that has a package or module named "token", it will fail:

Traceback (most recent call last):
  File "", line 189, in _run_module_as_main
  File "", line 148, in _get_module_details
  File "", line 112, in _get_module_details
  File "src\black\__init__.py", line 6, in 
    
  File "C:\Program Files\Python312\Lib\tokenize.py", line 36, in 
    from token import EXACT_TOKEN_TYPES
ImportError: cannot import name 'EXACT_TOKE...
dusk plinth
flat krakenBOT
umbral shell
#

Anyone has any python formatter working in jupyter notebook on vscode?

#

I can't get anything to work for formatting

flat krakenBOT
umbral shell
#

Apparently it tries to format it but fails

  File "Z:\Programs\Scoop\persist\vscode\data\extensions\ms-python.black-formatter-2024.0.1\bundled\tool\lsp_server.py", line 163, in is_python
    ast.parse(code, file_path)
  File "C:\Python312\Lib\ast.py", line 52, in parse
    return compile(source, filename, mode, flags,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "z:\pathtoproject\3. ocr.ipynb", line 1
    {
    ^
SyntaxError: invalid syntax
umbral shell
#

it's trying to format it like if it was a python file?

#

Bruh it works on cli it's just the dumb extension

#

how do you mess up an extension that only has to call an external binary

flat krakenBOT
#

Description

I was just about to start testing things, and was running into failed tests on main. Both test_invalid_gitignore and test_invalid_nested_gitignore both threw errors because of the case-sensitivity of "s" in "STRING" with gitignore being c:\\... and the output having C:\\....

On windows the path FoObAR is the same as foobar, so the output of black on a windows machine could output the path to .gitignore with upper or lower-case portions of the path. ...

flat krakenBOT
silent knoll
dense jungle
silent knoll
#

oh nvm diff-shades is still faling hm

flat krakenBOT
#

Describe the bug

A function with type parameters gets formatted incorrectly if the function parameters have a magic trailing comma.

To Reproduce

For example, take this code:

def func1[T](a,): pass
def func3[T,](a,): pass
def func3[T,](a,) -> R[X, Y,]: pass

And run it with these arguments:

$ black file.py --target-version py312

The resulting code is:

def func1[
    T
](a,):
    pass


def func3[
    T,
](a,):
   ...
flat krakenBOT
#

Description

This change adds additional checks to the choice of whether to split a funcdef from the left or right-hand side.
Specifically, this adds the following condition to should_split_funcdef_with_rhs:
If a funcdef has type parameters and its parameters also have a trailing comma, return True, to indicate that the funcdef should not be split from the left first.

This fixes the bug described in #4254.

I am currently trying to also fix #3929 and #4071 since they seem rel...

flat krakenBOT
#

Describe the bug

Black reformats the following .pyi stub file:

def foo(): ...

@decorator
class Bar: ...

to this:

def foo(): ...
@decorator
class Bar: ...

If Bar does not have a decorator, black permits the empty line between the two definitions. I think the empty line improves readability here quite a bit, so I'd prefer it if black would allow (or even enforce it). Decorated classes haven't historically been very common in stub files (previ...

flat krakenBOT
#

The change log is immensely useful, however it makes reference to specific Github issues and only mentions the issue number without actually linking to the issue.

I would like for the changelog to actually include links to the issue. It would be of great help to readers to be able to see the contextual discussion for a change, particularly for style changes.

https://black.readthedocs.io/en/stable/change_log.html

flat krakenBOT
flat krakenBOT
#

Currently, Black doesn't affect the order of import statements (or the order of their imported objects). I'll be surprised if this hasn't been brought up already, because it would highly improve the reproducibility of the the formatter. Plus, having imports in a sorted way lets you go through them faster (and is generally easier to read). There are a couple of potential problems though, and I've listed them at the end of this request.

Here's the rules (examples given below):

  1. Imports ...
flat krakenBOT
potent maple
#

Hello everybody, I am new here. I am building a playground webpage for black using pyodide (a wasm build of python) and modern js: https://black.py3.online . I think maybe we can update the old black playground in the docs: https://black.vercel.app ? I am a loyal user of black for a few years, and I want to recommend it to my friends, they check the docs site and visited the old playground web app, but that requires a backend and the latency is high. The implementation of mine is still very simple, it is now just a showcase, I wonder if there is opportunity to replace the old playground.

Learn black code style right in your browser

Playground for Black, the uncompromising Python code formatter.

#

You can edit in the left and formatted code in the right panel will sync in milliseconds

dense jungle
#

if that is added, I'd be open to adding a link to your site to our docs

#

another useful feature could be to let users select a version of Black

#

though that may be harder to implement

potent maple
#

At least the same set of options like the original playground can be implemented

#

And allowing user to choose the version of black is also possible

#

I will update my progress here if I've done all the things above. Thanks again~

flat krakenBOT
potent maple
#

I have a question, older version of black maybe do not expose the format_str API, or the Mode's signature is different

flat krakenBOT
#

Describe the style change

As of version 24.1.0, Black now wraps multiple context managers in parentheses #3489

This is a great feature, but in some cases it's a bit too eager to reformat. When the line only overflows because of the last context manager in the with statement, wrapping everything in parentheses is a bit redundant and takes up a lot of vertical space. Previously, if the last context manager was already formatted to wrap over multiple lines, Black would leave it unchang...

dense jungle
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Line ranges seem to format an entire file when the range goes to the end of the file

https://github.com/microsoft/vscode-black-formatter/issues/472

  • Take a file that is unformatted
  • Set the line ranges to any portion as long as the last line is EOF
  • The entire file is formatted

For example, take this code:

abc = 'def'
ghi= 'jkl'
mno='pqr'
stu='vwx'

And run it with these arguments:

black --line-ranges 4-5 file.py

~The resul...

flat krakenBOT
#

// SPDX-License-Identifier: GPL-2.0-only
/******************************************************************************


**
** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
** Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
**
**


*********************************************************************...

sharp root
flat krakenBOT
#

I use imports inside functions to implement lazy module loading to improve startup time. Black reformats imports within functions by adding an additional empty line this way:

async def start_web_interface(app, port):
    import uvicorn

    uv_config = uvicorn.Config(app, port=port)
    server = uvicorn.Server(uv_config)
    return await server.serve()

Desired style

async def start_web_interface(app, port):
    import uvicorn
    uv_config = uvicorn.Conf...
hollow pelican
#

Hi!
Please, help me. I have strange behaviour using different version of black.
When I work in IDE or in console python black formatting produces one result, but when I call pre-commit with https://github.com/psf/black-pre-commit-mirror it formats code different way. Could you explain how it happens? I use default configuration.

GitHub

Contribute to psf/black-pre-commit-mirror development by creating an account on GitHub.

flat krakenBOT
#
kwk

Describe the style change

I wonder if f-strings should be formatted at all.

Examples in the current Black style

print(f"{"|".join(['a','b','c'])}")

Desired style

print(f"{"|".join(['a','b','c'])}")

[!NOTE]
There's no change to the input here.

Additional context

Black formats the "|" to become " | " and that affects the output which cannot be desired.

Black formats the snippet like this currently:

flat krakenBOT
#

Description

Fixes #3793.

Now the if clauses in the case-match blocks will be correctly wrapped with parenthesis.

The previous problem of having redundant parentheses being added to case statement when it's accompanied with an if clause that are too long like the example mentioned in #3793 discussion is also resolved.

Checklist - did you ...

  • [x] Add an entry in CHANGES.md if necessary?
  • [x] Add / update tests if necessary?
  • [ ] Add new / update o...
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

When using a ternary statement within a string template, Black fails to parse the string if the quotes used within the template are the same as the template string.

To Reproduce

This fails:

cmd.append(f"--{"no-" if not do_continue else ""}continue")

With the following error (per the playground):

Cannot parse: 1:17: cmd.append(f"--{"no-" if not do_continue else ""}continue")

But this will pass:

cmd.append(f"--{'no-'...
flat krakenBOT
#

Description

This is intended to fix issues like #3929, #4071, and #4254, where the addition of the new type parameter syntax in Python 3.12 has caused suboptimal formatting of function definitions.

The new transformer for function definition inspects the given function definition, then splits at the first thing found from the following list:

  • function parameters with magic trailing comma
  • return type with magic trailing comma
  • type parameters with magic trailing comma
    ...
cloud spruce
#

/8847007269

flat krakenBOT
#

Description

This fixes #4264. The issue was that the empty last line does not count as a line to adjusted_lines because it is not in the list returned by str.splitlines. Since adjusted_lines is only called on the second pass of _format_str_once in format_str, the first pass would format the code correctly, then the "invalid" line would get removed from lines, and the second pass would format the whole code.

I added a small change to adjusted_lines to cap the end va...

flat krakenBOT
#

My CI keeps failing because I have used the black formatted in my code. Its hard to reproduce, and only happens intermittently when I run a lot of tests. Is there perhaps a better way to use black?

To Reproduce

For example, take this code:

import black

py_code = black.format_str(py_code, mode=black.Mode())

And run it with these arguments:

$ pytest -n 2

The resulting error is:

Step #2: pytest_1    | ______________________ test_all_sl...
sharp root
#

I'm having an extremely weird issue where tox -e py reports two tests as failing if I add any new file to tests/data/cases/.

It's really:

$ rm -rf .tox
$ tox -e py  # 367 passed, 1 skipped
$  echo "pass\n\n# output\npass" > tests/data/cases/some_test_case_name.py
$ tox -e py  # 2 failed, 366 passed, 1 skipped
FAILED tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_exclude - AssertionError: assert [] == [PosixPath('_...xclude/a.py')]
FAILED tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_extend_exclude - AssertionError: assert [] == [PosixPath('_...xclude/a.py')]

It's those two tests, consistently. When tested with a debugger, they don't fail.
The test session info:

platform linux -- Python 3.12.1, pytest-8.1.1, pluggy-1.4.0
cachedir: .tox/py/.pytest_cache
rootdir: /home/sumezulike/PycharmProjects/black
configfile: pyproject.toml
plugins: cov-4.1.0, xdist-3.5.0

The issue doesn't appear when running tox -e ci-py, but I don't want to push a potentially broken state.
Any suggestion how to proceed here?
...
I've found some correlation to the pytest --numprocesses parameter...
Those two tests fail consistently with the numprocesses values auto (4 for me), 4, 6, and 8.
They don't fail with --numprocesses 1, 2, 3, 5, 7, 9, 10, 11, 12.
...
I've found something different: My last change had added tests, bringing the total pytest collected items to 368. If I remove any one of the test parameter sets, reducing the test item count to 367, everything runs smoothly. If I remove another, I can add my test case file and all is good. Seems like an issue with multiprocessed testing but 367 is such an arbitrary number.
I'll try to make it as simple as possible to reproduce and write an issue but if it's not only weirdness on my machine, that's probably going to become an issue very soon anyways.

flat krakenBOT
dense jungle
sharp root
#

367 tests should really be enough though, right...? lemon_clown

#

Could you reproduce it?

dense jungle
#

Sorry, haven't tried yet

north quartz
#

hi

#

pls help me

#

code

#

pls

echo pebble
#

Hello
I think i have found a bug
I am sorry if it is a duplicate:
I am using python3.12

error: cannot format

Logger(__file__).critical(f"Error: {data_str[key]["error"]}")

But it works like this ( notice the ' before the f string)

Logger(__file__).critical(f'Error: {data_str[key]["error"]}')
dense jungle
flat krakenBOT
flat krakenBOT
#

black might destroy ascii art in dosctring when re-indenting docstring lines.

Example code:

def dosctring_ascii_alignment():
    """Ascii art: [____,aaaa,bbbb]
                   ^         ^
    """
    pass

result after 'black`:

def dosctring_ascii_alignment():
    """Ascii art: [____,aaaa,bbbb]
    ^         ^
    """
    pass

as seen, the carets ^ are now misaligned. This can in problematic cases destroy information and be very confusing, misle...

sharp root
#

Tiny question about the review process, do you expect the PR author to click the "Resolved" button when a change is completed or to react in some other way and the reviewer resolves the conversation?

dense jungle
flat krakenBOT
#

Is this related to a problem? Please describe.
I have a Flask app deployed to Heroku. When I submit my codebase to Heroku CI and execute black . --check --skip-string-normalization, Black tries to parse files that are injected by Heroku and that are not contained in my Github repo. This is a sample of the error messages I get:

-----> Running test command `black . --check --skip-string-normalization && vulture && flake8 && pytest --envfile tests/.env.integrationtest`...
would ...
flat krakenBOT
dense jungle
#

^ update Black or get ReDoSed

flat krakenBOT
tender night
#

Auto-formater users, have you found the lint rule number for having comment strings be started with a space (# comment instead of #comment)? I have a workflow where I distinguish commented-out blocks of code from text comments visually; having text comments be like # text-comment, and code-blocks like #commented-code. I guess it's an unusual problem, but by any chance, does anybody know how to stop ruff adding a space to latter formatting of comments?

flat krakenBOT
#

Describe the bug

When using the match-case block with a case case statement (syntax allowed since Python 3.10), Black fails to parse the code if the line length is set to a small number.

To Reproduce

Consider the following code:

match test:
    case case if True:
        pass

This code can be correctly formatted by Black when the line length is reduced to 14, as shown below ([playground link](https://black.vercel.app/?version=stable&state=_Td6WFoAA...

young sand
astral meteor
#

I installed black.vim with vim-plug and when I call Black I get the error, "The black.vim plugin requires vim7.0+ with Python 3.6 support".
lua print( vim.v.version ) returns 801 and I had python 3.11 and 2.7 installed. Tried uninstalling python2.7 but that did not work.

flat krakenBOT
#

Describe the style change
Allow aligning dict values in dict literals.

Examples in the current Black style

DATA = {
    "aa": 0x000F,
    "bbbb": 0x00F0,
    "cccccccc": 0x0F00,
    "dddddd": 0xF000,
}

Desired style
Having aligned values can aid readability in some cases.

DATA = {
    "aa":       0x000F,
    "bbbb":     0x00F0,
    "cccccccc": 0x0F00,
    "dddddd":   0xF000,
}

If the values are already aligned, that could be an...

flat krakenBOT
#

Describe the bug

Black hits me with this error when trying to format something

error: cannot format ...\test.ipynb: Cannot parse: 4:31: plt.savefig(f"output/_{config["year"].replace("/", "_")}.png", bbox_inches="tight")

Oh no! 💥 💔 💥
1 file failed to reformat.

To Reproduce

Take the code below and try to format it from the command line

For example, take this code:

import matplotlib.pyplot as plt

config = {"year": "2024"}
plt.sav...
flat krakenBOT
#

Describe the bug

Black reports an internal error with certain long f-strings as it tries to break the line in a syntactically invalid place.

To Reproduce

For example, take this code:

something = []

test_string = f"this is a really string that will be line broken at 120 chars that contains an interpolated join {",".join(something)}"

And run it with these arguments:

$ black file.py -l 120 --target-version py312

The resulting error is:
...

dense jungle
#

yay more duplicates

flat krakenBOT
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

When using black's GitHub action "psf/black", you need to specify the black version to use manually as an option to the action, in addition to specifying it in pyproject.toml. This can easily lead to inconsistencies between the files, especially when using dependabot to keep the version current.

Describe the solution you'd like

It would be useful if the action could read the version to use from pyproject.toml. Thi...

frigid island
#

I installed black==24.2.0 package and added it to my Pycharm plugins.
It is by default deleting unused imports or fully commented functions. How do I turn this off.

red sedge
#

Not black

frigid island
#

it worked. Thanks

flat krakenBOT
flat krakenBOT
flat krakenBOT
vale wharf
#

Btw, love the formatter, it's great 🥰

flat krakenBOT
#

Describe the bug

When reformatting a triple-quote string, black fails with an internal error.

To Reproduce

Take this code:

if __name__ == "__main__":
    """     This string...
    ... will confuse black.
    
    """
    pass

And run it with these arguments:

$ black file.py

The resulting error is:

error: cannot format blackerrdemo.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report ...
flat krakenBOT
vapid urchin
#

?

clever peak
#

!resources

late dewBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

frank fox
#

hi guys

flat krakenBOT
#

Thanks for all your work here!

I ran this PR branch on the mypy codebase with -t py312 and noticed some issues:

         if missing_error_codes:
             raise ValueError(
-                f"Some error codes are not documented: {', '.join(sorted(missing_error_codes))}"
+                f"Some error codes are not documented: {", ".join(sorted(missing_error_codes))}"
             )
 

We shouldn't change the quote style here.

     assert match is not None, f...
mint barn
#

Hello guys,
Can anyone explain me please, if I can have only one pyproject.toml, but specify the different line lenght for the subfolders?

[tool.black]
line-length = 88

[application.subfolder.tool.black]
line-length = 120

I have tried as above, but it doesnt seem to work

flat krakenBOT
#

Describe the bug

Black strips () from a tuple containing a single entry.

To Reproduce

For example, take this code:

class Transaction(Model):
    __table_args__ = (UniqueConstraint("entry_a_id", "entry_b_id"))

Black produces:

class Transaction(Model):
    __table_args__ = UniqueConstraint("entry_a_id", "entry_b_id")

This doesn't work with SQLAlchemy's expectation, causing errors:

sqlalchemy.exc.ArgumentError: __tab...

flat krakenBOT
#

Description

This adds an use_pyproject input to the GitHub Action that – when set to true – will read the black version from pyproject.toml file. Either from the project.dependencies array or one of the arrays from the project.optional-dependencies table.

Closes: #4285

Checklist - did you ...

  • [ ] Add an entry in CHANGES.md if necessary?
  • [ ] Add / update tests if necessary?
  • [x] Add new / update outdated documentation?

Trial runs at: https://github.c...

flat krakenBOT
sharp root
flat krakenBOT
flat krakenBOT
#

Thanks, but this is way too much detail. It's longer than the actual introduction to Black itself!

I'd be okay with a single sentence like "If you use pipx, you can install Black with pipx install black".

But even that probably has very limited value...
If you know what pipx is, you know that you can do this
If you don't know what pipx is, there isn't a reason why Black should teach you and why that should be a thing standing between you and formatted code

flat krakenBOT
#

Describe the bug

Specific placements of standalone comments, primarily in list comprehensions, will cause parsing errors.
These are actually formatting errors; black generates invalid code on the first run of _format_str_once, which then can't be parsed.

To Reproduce

I stumbled over two cases while working on #4026:

[
    x for
    # comment
    x, y in ["AB",]
]

causes

Cannot parse: 9:0: ]

This is because the code is first split at `# commen...

flat krakenBOT
#

Describe the bug

Every time I run black, it changes the same files back and forth between different representations of formats like shown in this diff:

-                self.dupe_isotope_compounds[
-                    "original"
-                ] = dupe_orig_compound_isotope_labels
+                self.dupe_isotope_compounds["original"] = (
+                    dupe_orig_compound_isotope_labels
+                )

To Reproduce

For example, take this co...

flat krakenBOT
#

When working on a project where the package or files are located on a network drive, the formatting failes due to the double backslash present in the network path. ie.

\\192.168. 0.2\MyShareFolder

To reproduce, move any python file to a network drive ie. a NAS server and try formatting there.

Error message:

[info] [Trace - 14:40:57] Received response 'textDocument/formatting - (4)' in 62ms. Request failed: tomllib.TOMLDecodeError: Unescaped '\' in a string (at line 9, column...
blissful crypt
#

hello yal

flat krakenBOT
#

I am using black version 24.3.0 and have set line-length = 88 in my config file, however running black . command doesn't modify the lines of code that are over 88 characters.

Ex:
Before running black
str = "this is the longest text in the history of mankind that I have seen in the world for all the good and bad things"

After running black the result is still the same. I don't see any error it says x file(s) left unchanged.

Here is my config file

max-...
flat krakenBOT
flat krakenBOT
#

Description

This pull request addresses the issue #4263, this pull request updates the Installation instructions in the Getting Started section under Installation sub-section of the documentation. It adds a line informing users about how to install Black using pipx.

Changes Made:

  • Added a line to the Installation section under Getting Started, advising users to install Black with pipx install black.

Snapshots for before changes and after changes made:

  • Before ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
deft patrol
flat krakenBOT
#

Describe the bug

When docstrings that are ignored by the Python interpreter (e.g. in if statements) are reformatted, it causes the

To Reproduce

This very simple program can reproduce the error:

if True:
    """
test
    """

The resulting error is:

[cannot format file.py: INTERNAL ERROR: ...](error: cannot format file.py: INTERNAL ERROR: Black produced code that is not equivalent to the source. Please report a bug on https://github.com/psf/...

flat krakenBOT
#

Describe the bug

It fails on .replace('"', "'").

To Reproduce


output_folder = "Output"
row = {'name': '"Sample Movie"'}

file_path = os.path.join(output_folder, f"{row['name'].replace('"', "'")}.md")
print(file_path)

And run it with these arguments:

$ black file.py

The resulting error is:

INTERNAL ERROR: Black produced code that is not equivalent to the source.

Environment

  • Black's version: 24.4.0
  • OS and Pytho...
flat krakenBOT
flat krakenBOT
#

Fixes #3545

Description

I added this to the hug_parens_with_braces_and_square_brackets unstable style since there was a lot of overlapping code. I renamed it to concise_nested_brackets to reflect this. That is a breaking change if anyone was using --enable-unstable-feature hug_parens_with_braces_and_square_brackets, but to my knowlege, the existence of certain unstale features is not gurenteed to be stable. I can add the old name back as a (deprecated) alias or revert the rena...

flat krakenBOT
#

Description

I noticed that, if the github action is called in an unexpected way (such as from https://github.com/nektos/act), substitution of .git_archival.txt can be not performed.
For that cases, the action tries to execute pip install black[colorama]==$Format:%(describe:tags=true,match=*[0-9]*)$, which is not making any sense.
This PR is trying to fix this behavior.

Checklist - did you ...

  • [ ] Add an entry in CHANGES.md if necessary?
  • [ ] Add / upda...
flat krakenBOT
#

Describe the bug

black fails to parse or reformat the following valid Python sentence:

   print(f"PRN {sat["PRN"]}: {sat["DF398"]}")

To Reproduce

Execute black against this code snippet:

sat = {}
sat["PRN"] = 32
sat["DF398"] = 0.1648652
print(f"PRN {sat["PRN"]}: {sat["DF398"]}")
$ black temp.py --target-version py39

The resulting error (with all target versions from py39 to py312) is:

error: cannot format ...
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

Consider a simple python script:

import numpy as np
a=np.arange(9).reshape((3,3))
print(a[1,2])
print(f"a[1,2] = {a[1,2]}")

Running black on this it would by default provide:

$ black --diff a.py
--- a.py        2024-04-19 01:29:28.562943+00:00
+++ a.py        2024-04-19 01:29:52.064944+00:00
@@ -1,4 +1,5 @@
 import numpy as np
-a=np.arange(9).reshape((3,3))
-print(a[1,2])
+
+a = np.ara...
flat krakenBOT
#

error: cannot format checkgo.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.

import re
import requests
import platform
from cansii import CAnsii as c






def banner_gopher():
    return c.blue(
    """

         ,_---~~~~~----._         
  _,,_,*^____      _____``*g*""*, 
 / __/ /'     ^.  /      \\\\ ^@q   f 
[  @f | @))    |  | @))   l  0 _/  
 \\`/   \\\\~____ / __\\\\_____\\\\    \\\\   
  |           _l__l...
flat krakenBOT
flat krakenBOT
#

Describe the bug

My precommit file:

repos:
  - repo: https://github.com/psf/black
    rev: 24.4.0
    hooks:
      - id: black

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.0.289
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]

etc.

My pyproject.toml file:

[tool.black]
line-length = 89

[tool.isort]
profile = "black"
skip = [".gitignore", ".dockerignore"]

I'm running this. Black sets line leng...

flat krakenBOT
#

Description

Per Issue #4291, Black previously failed to format function definitions that contained an empty line before an indented function stub. This change resolves this bug by removing any newlines in the prefix of the first dot in a function stub after a stub suite is found. We added this change in the visit_default() function of linegen.py.

Through this change, functions defined as below:

class C:
    def f(self):

        ...

are formatted as:

...
flat krakenBOT
#

Describe the bug

A long string literal doesn't get split.

To Reproduce

For example, take this code:

x = "aaaaaaaaaa bbbbbbbb cccccccccccc dddddddddddddd eeeeeeeeeeee fffffffffffffffff ggggggggggggggg hhhhhhhhhh"

And run it with these arguments:

$ black file.py

The file is left unchanged.

Expected behavior

The string gets split into something like:

x = (
    "aaa ..   . fff"
    "fff ... gggggggggg.."
)

...

flat krakenBOT
#

Thanks for the PR! It's a little scary to me to be changing visit_default. Can we change it in a more targeted way (e.g. specifically at the call sites in #3796 when we know we're dealing with a stub body)?

As it stands, I think this will change formatting in other situations as well, for instance, if there are real statements after ....

One nit: let's move the test cases into tests/data/cases/dummy_implementations.py?

flat krakenBOT
slow ibex
# flat kraken
>black --version
black, 24.4.0 (compiled: yes)
Python (CPython) 3.12.0

>black --preview -c "f'''{f'{x +1}'}'''"
f"""{f'{x +1}'}"""

>black --preview -c "f'{f'{x+ 1}'}'"
f'{f'{x+ 1}'}'
error: cannot format <string>: Cannot parse: 1:5: f'{f'{x+ 1}'}'
``` is this expected?
dense jungle
#

we haven't released that change yet, so yes

#

(and I'll hold off for some time on releasing to see if we can fix the issue above first)

flat krakenBOT
#

Thanks, these changes look good.

However, I think I'd prefer to keep feature names stable through the year. The main motivation for adding --enable-unstable-feature was to allow users who want to keep some feature on to just turn on the feature in their config and have it keep working.

Also, I don't want to accept a PR that directly adds a new unstable style. I see the unstable style as a holding pen for style changes that we'd originally put into preview but later ran into issues wit...

ornate prawn
#

error: cannot format serial_read_write.py: Cannot parse: 13:17: f'{r'\ '.replace(' ', '')}'

Why is black unable to parse this? Should i open an issue on github?

dense jungle
#

we just merged a fix, I'll release it this week

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

black hangs and does not exit.

To Reproduce

$ python3 --version
Python 3.10.12
$ python3 -m venv venvblack
$ ./venvblack/bin/pip install black==24.4.1
Collecting black==24.4.1
  Using cached black-24.4.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.8 MB)
Collecting typing-extensions>=4.0.1
  Using cached typing_extensions-4.11.0-py3-none-any.whl (34 kB)
Collecting packaging>=22.0
  Using cached packaging-24.0-py3-none-any.whl (5...
flat krakenBOT
#

Fixes #4330

I found that the repro case from #4330 was hanging in applying some of the regexes used in tokenization. These regexes have a few inefficient features:

  • Nested and adjacent groups instead of a single level; this leads to backtracking
  • Some of the groups for "normal" characters were missing an exclusion for backslash, which was also leading to backtracking.
flat krakenBOT
flat krakenBOT
#

Hi.

Not sure if this is a bug or more of a feedback request, but was just wondering about certain thing.
Describe the bug

If writing a logical statement in Python, black doesn't delete unnecessary brackets.

To Reproduce

For example, take this code:

a = (not False) or True

after formatting with black, the brackets stay

Is this an expected behavior?

isn't the above code, identical to:

a = not False or True

As far as I rememb...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Python 3.10.14 and pytest 8.1.1.
Looks like something is wring with latest version because it started failing in pytest on collecting units.

+ PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-black-24.4.2-2.fc37.x86_64/usr/lib64/python3.10/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-black-24.4.2-2.fc37.x86_64/usr/lib/python3.10/site-packages
+ /usr/bin/pytest -ra -m 'not network'
====================================================================================...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Is this related to a problem? Please describe.

It would be nice if one could copy-paste links to the https://black.readthedocs.io/en/stable/change_log.html doc with anchors to specific versions.

ATM the page seems to put idX anchors on each header,
where X is an incrementing number.

This means that over time the underlying content changes (with each release)
and there seems to be no way to point people to a specific section (version) of that doc
regardless of what the mo...

flat krakenBOT
flat krakenBOT
young sand
flat krakenBOT
#

Description

Closes #4258.

This adds a listener to the sphinx include-read event to find all PR numbers (#X) with regex and replace them with the corresponding link [(#X)](https://github.com/psf/black/pull/X).

I didn't add an entry to CHANGES.md since this seems like a rather minor docs change.

Checklist - did you ...

  • [-] Add an entry in CHANGES.md if necessary?
  • [-] Add / update tests if necessary?
  • [-] Add new / update outdated documentation?
    ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

black cannot format this type of code: f"{'\''}"

$ black foo.py
error: cannot format foo.py: Cannot parse: 1:3: EOF in multi-line string

Oh no! 💥 💔 💥
1 file failed to reformat.

I was thinking that it might be the same bug as https://github.com/psf/black/issues/4334, but the example in that issue (f'{'a'}') doesn't produce an error in black 24.4.2 anymore, and Python 3.12.2 accepts the above code:

import ast
from pathlib import ...
flat krakenBOT
#

Describe the bug

See the code example.

To Reproduce

test = {"asdf" : 23} 

f"test['asdf']: {test["asdf"]}"

The resulting error is:

[cannot format file.py: INTERNAL ERROR: ...](error: cannot format /format_test.py: Cannot parse: 3:23: f"test['asdf']: {test["asdf"]}")

It fails at the first " inside the f-string's code block when indexing the dictionary.

As a note, the online formatter actually gives a different error, which makes even l...

flat krakenBOT
#

Describe the style change

Concatenated list comprehensions should be put one-per-line rather than splitting within a comprehension.

Examples in the current Black style

            matching_routes = [r for r in routes if r.get("dst") and ip in ipaddress.ip_network(r.get("dst"))] + [
                r for r in routes if r.get("dst") == "" and r.get("family") == family
            ]

Desired style

            matching_routes = (
                [r fo...
flat krakenBOT
#

Can not format this code

class Or:
    def __init__(self, rs) -> None:
        self.rs = rs

    def __str__(self):
        return f'Or({','.join(self.rs)})'

    def __repr__(self) -> str:
        return str(self)
  1. Update Black's version if a newer release exists: pip install -U black
    Already updated
  2. Use the online formatter at
    Still can not format

To Reproduce

Copy these code to a file, and format it by VSCode.

Run argumen...

flat krakenBOT
#

Describe the style change

I have found the way black is handling inline generics ie def f[T](...) a little unexpected and less consistent with prior style.

Examples in the current Black style

[tool.black]
line-length = 119
target-version = ['py312']

Using non inline generics, the function is split along the arguments, this is expected.

T = TypeVar("T", bound=float)

def function_name(
    x1: datetime.datetime, x2: datetime.datetime...
flat krakenBOT
#

Describe the bug

Strings longer than my set character limit (79) don't get formatted like the rest of the code.

To Reproduce

For example, take this code:

string = "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test"

Expected behavior

A string split over 2 lines.

Environment

  • Black's version: v2024.2.0
  • OS and Python version: Window...
neon loom
neon loom
#

O, I didn't test blackd

#

Idiot

flat krakenBOT
#
  • Lets install black, then ask to install black with extrasC
    • pip sees black is installed and just installs extra dependencies

Test:

  • Build local container
    • docker build -t black_local .
  • Run blackd in container
    • docker run -p 45484:45484 --rm black_local blackd --bind-host 0.0.0.0
cooper@home1:~/repos/black$ docker run -p 45484:45484 --rm black_local blackd --bind-host 0.0.0.0
blackd version 24.4.3.dev11+gad60e62 listening on 0.0.0.0 port 45484
INFO:aiohttp.acc...
neon loom
#

Got the fix.

#

I doubt we should log a bug with pip as I don't think pointing pip @ wheels should respect extras installs - I'm happy with running pip twice ...

#

Maybe it could error since it seems to ignore it ...

flat krakenBOT
#

Describe the bug

For a particular string in my source, it is not able to format.

To Reproduce
Please see below output produced by black

--- src
+++ dst
@@ -81541,11 +81541,11 @@
             value=
             Constant(
                 kind=
                 None,  # NoneType
                 value=
-                "\n    ===============================================================================================\n    \n    # NOTE: when parquet gener...
flat krakenBOT
#

Black versions 24.4.1 and 24.4.2 encounter an issue when formatting Python code containing an f-string that includes a multi-line string. Example:

s = f"""{'''a
            b
            c'''}"""

print(s)

this is valid python syntax, as it is executable, but black cannot format it, as indicated below:

>>> cat black_sample.py 
s = f"""{'''a
            b
            c'''}"""

print(s)

>>> python --version
Python 3.12.1

>>> python black_sample....
flat krakenBOT
bright glacier
#

This isn't the right place to show off your project. This is the channel for the Black autoformatter project as the channel description states.

flat krakenBOT
#

Describe the bug

Running UFMT lint on PyTorch main branch code, and has following error message.

$ lintrunner -a --take UFMT test/quantization/**/*
Warning: Could not find a lintrunner config at: '.lintrunner.private.toml'. Continuing without using configuration file.
WARNING: The init commands have changed since you last ran lintrunner. You may need to run lintrunner init.

Lint for test/quantization/fx/test_quantize_fx.py:

Advice (UFMT) command-failed
Fai...

austere turtle
late dewBOT
#

server/config/context_processors.py line 15

"downloads_page_donation_message": config.SHIPPER_DOWNLOADS_PAGE_DONATION_MESSAGE,  # noqa: E501```
dense jungle
#

if this is important to you you can manually reformat the line (I think if you put parens around the config.SHIPPER_... black might put it on multiple lines)

austere turtle
#

yup, but if I try and split it then black merges it back again. I'm wondering if there's a config issue I'm not picking up on.

dense jungle
#

personally I'd just disable lint rules about line length, it's not worth the trouble to deal with the manually in the rare cases where Black can't handle line length

austere turtle
silent knoll
#

fyi - the --unstable style attempts to add parens here, but it's broken in this specific case due to #4158, i'm trying to fix this rn

flat krakenBOT
#

Hello, I believe I have found a bug in how black handles fmt: skip. Consider the following snippet:

t = (
    {"foo": "very long string", "bar": "another very long string", "baz": "we should run out of space by now"},
    {"foo": "bar"},
)

Without any changes, the line with first dictionary is 114 characters long and should be reformatted by black, which has a default line length limit set to 88 characters.. Second line is only 18 characters long and should be left ...

flat krakenBOT
flat krakenBOT
flat krakenBOT
grand cipher
#

I can't tell if this change was on purpose or accidental:

The --preview style in 24.1.1 was much more compact and very much preferable. Here's an example diff (of --preview style) moving from 24.1.1 to current latest (24.4.2).
https://gist.github.com/bukzor/33512c19ab47607a733fd8396adb3522

 def get_added_but_ignored_files() -> set[Path]:
-    return set([
-        Path(path)
-        for path in sh_lines((
-            "git",
-            "ls-files",
-            "--cached",
-            "--ignored",
-            "--exclude-standard",
-            ".",
-        ))
-    ])
+    return set(
+        [
+            Path(path)
+            for path in sh_lines(
+                (
+                    "git",
+                    "ls-files",
+                    "--cached",
+                    "--ignored",
+                    "--exclude-standard",
+                    ".",
+                )
+            )
+        ]
+    )
Gist

GitHub Gist: instantly share code, notes, and snippets.

dense jungle
grand cipher
#

okay so i want to enable that unstable feature... looking.

#

i'm guessing fixing the crash isn't simple? or else i might try

#

i had checked --unstable but still saw the regressed style

grand cipher
#

this improves my quality of life. Thanks!!

--- a/pyproject.toml
+++ b/pyproject.toml
+enable-unstable-feature = [
+  'hug_parens_with_braces_and_square_brackets'
+]
dense jungle
late dewBOT
#

src/black/mode.py line 218

# See issue #4036 (crash), #4098, #4099 (proposed tweaks)```
grand cipher
#

do you have any estimate for difficulty of fixing the crash?

dense jungle
#

I'm not sure, I haven't looked in much detail

flat krakenBOT
#

Is this related to a problem? Please describe.

I'm new to black in terms of contribution. I'd like to work on this issue #4353, but I'm struggling to understand the basics of data structures and the flow of black. I searched the black's website and GitHub issues but didn't find something useful for this issue.

Describe the solution you'd like

I'd like to have a technical document explaining the logic of black.

Describe alternatives you've considered

**Additi...

flat krakenBOT
flat krakenBOT
flat krakenBOT
topaz osprey
# flat kraken

Please check this pr and let me know if i need something to be changed

flat krakenBOT
topaz osprey
#

Hey @dense jungle can you check my pr

flat krakenBOT
#

Describe the bug

Black fails to format an f-string, containing a triple quoted string, that has a new line in it.

To Reproduce

For example, take this code:

a = f'''{"""
"""}'''

And run it with these arguments:

$ black file.py

The resulting error is:

error: cannot format a.py: Cannot parse: 1:9: a = f'''{"""

Expected behavior

The file should be formatted. I am not sure how this should get formatted though. The code is vali...

proper swift
#

On version 24 when installing black using poetry I can't get the dependencies, while on version 23 it works fine.

red sedge
mint barn
#

Guys I'm so enthusiastic about contributing to open source. But wondering how. What skills should I possess if I want to contribute to ML related projects?

flat krakenBOT
flat krakenBOT
flat krakenBOT
solemn mantle
#

just question do i have to use pip or can i use conda to install the black formatter

#

plus is it fine running black on jupyter notebooks

dense jungle
dense jungle
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
topaz osprey
#

Should I try this ? @dense jungle the long comment error

dense jungle
topaz osprey
#

Thanks for the reply, No worries I get it my pr are heavy then normal pr's. But whenever you review it just let me know if you want to change some approach or have any questions.
Hope you have a good day

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

Just writing black to the command line outputs:

Usage: black [OPTIONS] SRC ... One of 'SRC' or 'code' is required.

Describe the solution you'd like

Make the functionality of black without parameters work like black $(pwd) (excecuting black on working directory)

flat krakenBOT
midnight vector
#

Guys efficiency wiss which IDE is better? Pycharm or VSCode or Jupytr Notebook?

silent knoll
#

I've always used VSC. Jupyter honestly didn't feel very intuitive to me, but the Jupyter-in-VSC implementation works well imo. Never used Pycharn

(although i don't believe this is the correct channel for this question)

flat krakenBOT
#

I typically include a comment after an assignment to document the meaning of a variable, like so:
my_var = 0.1 # my_var is my variable

If my comment is too long, black will sometimes - but not always - split the assignment on to its own line:
my_var = ( 0.1 # this is an example black won't actually split this one. I have real examples shortly. )

However, this split occurs inconsistently for obscure reasons? In my testing, it appears to possibly related to the number of sho...

flat krakenBOT
flat krakenBOT
#

Describe the bug

Black produces different results in different environments for code containing curly braces when used with the same version and options

To Reproduce

[Linux/Python 3.9.17] or [Windows/Python 3.9.6]

$ black --version

black, 24.4.2 (compiled: yes)
Python (CPython) 3.9.17
$ black --target-version py39 --required-version 24.4.2 --line-length 120 --skip-string-normalization --check --diff --color -c "{}.update({'a': 1,})"

--- STDIN  ...
fossil rain
#

Hello all, I am trying to find alternatives for yamllint. Please suggest any options you have in mind.

celest bane
#

Hi Guys, In my current project, team is using teamforge as a version control tool. I want to implement black formatter so that developers adhere to coding standards, the problem is the version control we use do not have any cicd pipeline or github workflow or any automated process. It uses git as underlying software but the above features are not there. How do i impelement black formatter here? I tried pre-commit but its not useful because it has to installed locally first which most of people might not do. Is there an automated way to install pre-commit after cloning the repo?

#

Please help me. Thanks in advance!

hasty nebula
#

eu quero gozar mano

flat krakenBOT
#
  • So yeah my laptop is getting bogged down ......the crazy thing is I don't got a available AI that converts all coding into pytorch available to me where I can directly feed all the functioning programs into a full on formulated auto synchronized essembly like for example who says a virtual machine can't hold a updating security suite to duel protecting in house and out of house environment watchdoging my laptop if I ignore it with foresight like capability awareness and reactive intuition s...
dense jungle
#

wow the issue already got deleted. good work GitHub

slow ibex
#

i wonder how they produced this text

pure wigeon
#

is it possible to have the equivalent of --preview --enable-unstable-feature string_processing in a pyproject.toml file? I've tried

[tool.black]
line-length = 80
preview = true
enable-unstable-feature = ["string_processing", "multiline_string_handling"]

...but string processing is not happening

#

oop, that was my error, my editor did not have the right venv active

flat krakenBOT
flat krakenBOT
solemn mantle
#

evening. how will I know if the black formatter is working on a jupyter notebook? what small test should i do to check

flat krakenBOT
#

Missing indentation in special combination of long names in a output collection in tuple

Hello! I may have found an issue with the formatting, where it does behave differently only in special cases.

After an automatic line break following the opening parenthesis of a function call, an indentation of 4 spaces is expected.
I tried this in several simplified versions (shorter names), where it worked as expected, but in the given example, the indentation does not occur.

I tested wi...

flat krakenBOT
#

Hello, I recently hit a bug while working on adding type error suppressions to a codebase I'm working on.

Describe the bug

Black appears to add a Tuple to the AST when a comment is present in a multi-line return type annotation. This results in an ASTSafetyError and fails to lint the file.

To Reproduce

Run the following example file in the online editor

import typing as t

from my_library import Abstract
from my_...
flat krakenBOT
#

Hello Black team,

I am working as part of a research team developing a code analysis tool for Python. One of the issues the tool discovered in black's codebase is a MemoryError when formatting some Jupyter notebooks. In this case, the cause is due to a stack overflow in the Python parser. Attached is an ipynb file that reproduces the error on the latest version of black.

If you are interested in learning more about the tool and how it found this issue, let me know down in the comm...

flat krakenBOT
#

Resolves #4350

If a string like '\'' is inside a double-quoted f-string, like f"{'\''}" the formatter would break trying to remove the escaped \' quote.

This is because normalize_string_quotes looks at the entire f"{'\''}" input, and the outermost quotes ", hence determining that the \' escape is unnecessary.

To avoid these cases, we don't try to normalize inner strings inside f-string braces.

earnest sequoia
#

The following code passes locally (default arguments), but fails in the playground:

match True:
    case 1:
        def a():
            return 1
    case 1:
        def a():
            return 1

cannot use --safe with this file; failed to parse source file AST: invalid syntax (<unknown>, line 1)
This could be caused by running Black with an older Python version that does not support new syntax used in your source file.

dense jungle
#

we don't run it, can't do much about it unfortunately

short viper
#

yo guys sm1 want to star project for biggners

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Say I have this file structure:

my-project
├── large_ignored_dir
│   ├── a.py
│   ├── inner
│   │   └── b.py
│   ├── inner2
│   │   └── c.py
│   └── inner3
│       └── d.py
└── z.py

The only file I want black to pay attention to is z.py.

Then I run black --exclude='large_ignored_dir/' --check -v . which shows me:

Identified `/` as project root containing a file system root.
Found input source directory: "[...]/my-project"
[...]/my-project/large_ignored_di...
ivory yacht
#

bruh

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

This could be a user error, and if so, please let me know how to achieve the desired result :)

The documentation states that if we use version in the GitHub (GH) action workflow, valid version specifier per Python packaging standards can be used. This means we can do:

- uses: psf/black@stable
  with:
    options: "--check --verbo...
flat krakenBOT
#

I cannot use black to reformat my file. Here is the output of black --versbose test.py

  File "/usr/lib/python3.12/site-packages/black/__init__.py", line 902, in reformat_one
    if changed is not Changed.CACHED and format_file_in_place(
                                         ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/site-packages/black/__init__.py", line 944, in format_file_in_place
    dst_contents = format_file_contents(
        ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Is this related to a problem? Please describe.

Error in the Setup docs command pip install -e .[d], here [d] has no significance which causes an error while installing.

(.venv) kanishkpachauri in ~/Desktop/oss/Python/black on main λ pip install -e .[d]
zsh: no matches found: .[d]

Describe the solution you'd like

Remove [d] from the docs.

**Describe alternatives you'v...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Hello,

Why did you place the imports in different positions? The goal of the code is readability, which is lacking in your current format. Imports should be at the same position for better readability. This way, I can quickly recognize the imported modules. Compare my code style on the left with the Black code style on the right. Which do you think offers better readability?

image

flat krakenBOT
#

Describe the bug

Black fails to parse a file containing a multiline f-string that starts with a backslash \

To Reproduce

For example, take this code:

print """\
This is a multiline string
"""

And paste into https://black.vercel.app/?version=main

The resulting error is:

Cannot parse: 1:6: print """\

Example:

https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ACXAGJdAD2IimZxl1N_WmOQqEcOUhKyNfjwrEvHNPJJ-L3FEiTxKn...

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

I'd like to be able to use the GitHub release version of black on arm64 Linux hosts, but I can't.

Describe the solution you'd like

Produce an arm64 Linux GitHub release of black. Ideally, this would include changing the existing linux release to include the appropriate architecture in the release file name (presumably "x86-64").

Describe alternatives you've considered

There's not really an alternative he...

azure plank
# flat kraken

Sometimes I feel like I trigger Cunningham’s law in JelleZijstra with some of my replies :)

dense jungle
#

But yeah if I get another notification for an issue that can be a trigger to close it, especially if somebody else explains why it can be closed

azure plank
#

Those are my favorites to answer, since I can contribute without having to figure out the code

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Black fails to format a valid Python f-string containing \{. I minimized this from a file in Pygments, pygments/lexers/int_fiction.py.

% cat rf.py 
rf'{a}\{{[\}}'
% black --check rf.py
error: cannot format rf.py: Cannot parse: 1:10: rf'{a}\{{[\}}'

Oh no! 💥 💔 💥
1 file would fail to reformat.
% python rf.py 
Traceback (most recent call last):
  File "/Users/jelle/py/black/rf.py", line 1, in 
    rf'{a}\{{[\}}'
        ^
NameError: name 'a' is not defined
% python -V
Pyt...
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

After updating my project to use Black's formatting, I liked the readability of functions splitting each parameter into its own line.
I saw that there is a Preview feature "typed_params_trailing_comma" that seems like it would automatically add a trailing comma to typed function parameters regardless of line length.
When using the option, it didn't appear to do anything different compared to Black's default behavior.
I'm unsure of what the feature is supposed to do ...

flat krakenBOT
#

Description

Extend the docstring of black's find_project_root to mention that it ignores pyproject.toml files without a [tool.black] section.

This is relevant because that function is also used by other python packages that use black. I found that e.g. datamodel-code-generator uses that function and that there the ignoring of the pyproject.toml files lead to [a degradation](https://github.com/koxudaxi/datamodel-code-genera...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Is this related to a problem? Please describe.

The descriptions of many preview style features aren't very descriptive as they only have one sentence explaining each of them in the docs.
This can lead to uncertainty about how some of the preview features affect formatting.
Contrasting this to the unstable style features that have dedicated sections and examples explaining what they do, I feel that the preview style features should receive the same treatment.

**Describe the soluti...

flat krakenBOT
#

Describe the bug

Black's --line-ranges option does not completely prevent reformatting of code outside of the specified line ranges.

To Reproduce

For example, take this code:

print("format me"  )
 # format whitespace
  # format whitespace
   # format whitespace
print( "format me" )
   # format whitespace
  # format whitespace
 # format whitespace
print(  "format me")



print("don't format me"  )
 # don't format whitespace
  # don't format whites...
flat krakenBOT
#

Describe the bug

Black reports "cannot use --safe with this file; failed to parse source file AST: f-string: unmatched '[' (, line 1)"

To Reproduce

Take this code:

output = render(m,h=f"{dic["key"]}")

And run it with these arguments:

$ black file.py

The resulting error is:

error: cannot format test_black.py: cannot use --safe with this file; failed to parse source file AST: f-string: unmatched '[' (, line 1)
This could be caused ...

flat krakenBOT
#

Description

Resolves #4374
I'm new to contributing and was looking for small ways to improve the docs.
This is just a simple addition that I don't believe needs a changelog entry as small docs changes don't need an entry according to CHANGES.md.
I based my changes off how isort handles the defaults in their documentation: https://pycqa.github.io/isort/docs/configuration/options.html#skip

Checklist - did you ...

  • [n] Add an entry in CHANGES.md if necessary...
flat krakenBOT
heavy heron
#

Hey! Is there any documentation on what's the best way to introduce Black to an existing Git codebase?

#

I can put my config and run Black into one branch, but how do I avoid creating merge conflicts with every single other branch?

#

My first instinct was to run black on those other branches but it runs the same work twice and explodes

heavy heron
#

Thank youuu

bright glacier
#

IIRC I wrote that document. It evidently hasn't been updated since as there is zero guidance to deal with merge conflicts :)

elder tusk
flat krakenBOT
flat krakenBOT
#

When trying the black vim plugin in builtin vim in macOS 14, we get this unclear error message:

The black.vim plugin requires vim7.0+ with Python 3.6 support.

The issues is that the builtin vim is not compiled with python3:

% /usr/bin/vim --version | grep python3
+cmdline_info      +libcall           -python3           +virtualedit

No issue with vim from homebrew:

% /opt/homebrew/bin/vim --version | grep python3
+cmdline_info      +libcall           +...
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

It looks like everything is mostly working on the free-threaded build, except for three failing tests:

=========================== short test summary info ============================
FAILED tests/test_blackd.py::BlackDTestCase::test_normalizes_line_endings - AssertionError: '[Errno 24] Too many open files' != 'c\r\nc\r\n'
FAILED tests/test_blackd.py::BlackDTestCase::test_preserves_line_endings - OSError: [Errno 2...
flat krakenBOT
#

Describe the bug

I installed the VS extensions and tried to format a file.

In the log output it said it can't format the file and told me to report the bug.

To Reproduce

For example, take this code:

from typing import List
import requests
import json
import sys
from datetime import datetime, timedelta, time
from zoneinfo import ZoneInfo
from typing import NamedTuple
import locale

class Subcalendar(NamedTuple):
    name: str
    id: int

cl...
wind valley
#

Newbe question:

I have installed pip install black[jupyter] per the instructions on the project site. Is there a "cell magic" that'll enable black for all cells in my jupyter lab notebook such that anytime I execute a cell it'll overwrite contents with a black-formatted version?

Context:
I used to simply be able to do %load_ext lab_black and that used to work via nb_black package. However, pip install of that does not work anymore - it runs into a bug in the install scripts. newer pip versions assert version information to be in certain format. Also that project does not seem to be maintained.

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
bright glacier
#

!ban 1271167406747942988 Solicitation of paid work is not allowed here as per our rules, specifically rule 9. As you appear to have only joined to seek clients and have already been warned to stop, we are removing you from the community.

late dewBOT
#

:incoming_envelope: :ok_hand: applied ban to @echo tartan permanently.

flat krakenBOT
flat krakenBOT
#

Hi there,

I hope you’re doing well. I wanted to bring to your attention some potential license compliance issues related to a few third-party libraries in your project.

For example:

Library: aiohttp - License: Apache-2.0
Potential Issue: The Apache-2.0 license requires that the original copyright notice be included with any distribution of the software, and that the source code is made available. Additionally, any derivative works must be distributed under the same license.

...

bright glacier
#

is this automated...?

#

In fairness, the PyInstaller binaries may actually have some licensing issues as I think some of our dependencies are GPL-licensed and we probably don't include any third-party licenses, but this issue seems off the mark.

solemn shell
#

the only formatter i will ever use is the one builtinto golangs vscode extension

dense jungle
azure plank
#

(Not legal advice)
It looks like pyinstaller strips licenses, so unless something special is set up to counteract that almost all the licenses (that aren’t inside the source code) would be violated https://github.com/pyinstaller/pyinstaller/issues/5666
That does bring up the question, because of how pyinstaller works, the source code is literally included, so the GPL licenses might be fine?
I hate licensing so much, neither MIT or Apache-2.0 are clear enough that I know how to satisfy them, even with hours of research, so the only answers I have found so far are pray you don’t get sued since it’s impossible to satisfy, or pay thousands for a software licensing lawyer.

GitHub

The Pyinstaller process prunes all license information. For legal reasons, a standard python installation includes the Tcl/tk license because Tcl and Tcl/Tk are included. Similarly the MIT license ...

bright glacier
#

As long as we include the full license text of all of black's dependencies in the pyinstaller bundle, it should be fine.

tough magnet
#

Hi is there a way integrate open ai into an app??? Using python

flat krakenBOT
#

Description

Resolves #4399

Added an extra check before adding commas to the elements in the body of a bracket split.

The check ensures that there is more than just one non-comment item in the list of return elements. It only performs this check for a bracket split in return annotations as it's non-problematic for parameter annotations.

The extra comment was causing the ASTSafetyError (it led to the return type being interpreted as a tuple).

Checklist - did you ...

...

slow ibex
#

cool number

#

#️⃣4️⃣4️⃣4️⃣4️⃣

flat krakenBOT
spark zephyr
#

what is this project about?

lapis coyote
spark zephyr
#

can i still contribute any way?

#

i've never contributed on any github repo

hazy fable
#

improvement never really stops. for example I can see that the mobile version of the Black playground website can largely be improved in terms of UI :)

azure plank
flat krakenBOT
#

Describe the bug

Black running on M1 MacBooks does drop a few Characters of Python Source Code, when given these particular 120 Characters, but only sometimes. Sometimes you call Black and it works. Sometimes you call, and it chokes

To Reproduce

Visit an M1 MacBook and feed these 4 Lines of Python Code into Black

For example, take these 4 Lines, formatted exactly as shown

import argparse
import string


S1 = f"{argparse.OPTIONAL[:9]=}"
S2 = (string.ascii...
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Thank you for the PR!

I have a slightly different fix in mind. We should try and find a leaf that actually has the appropriate parent set. This will fix a similar crash in another case, see:

def foo() -> (
    # comment inside parenthesised new union return type
    int | str | bytes
):
    ...

I opened a PR with what I had in mind at https://github.com/psf/black/pull/4453. I'd be grateful if you had time to take a look and see if it makes sense to you!

flat krakenBOT
flat krakenBOT
#

Describe the bug

I have the black extension installed in VSCode. When trying to format a python file, VSCode showed the following error:

error: cannot format /****/test.py: 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_jfvgc9ph.log

The log file contains the following content.

--- src
+++ dst
@@ -30428,11 +30428,11 @@
                 value=...
flat krakenBOT
#

Describe the style change

I found a behavior that seems inconsistant when expressions are chained with operators. I feel like the most readable solution is to break on the operators which to be the chosen solution for normal statements but not in some cases

Examples in the current Black style

Given the following input code:

value = get_value_from_a_kinda_long_function() + previous_values[-1] + max(offset, threshold)

Black breaks the plus signs an...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

Black configurations are seemingly not taken into account for any paths after the first one passed to CLI - I'm seeing this in particular for "line-length" but have no reason to expect the behaviour is specifically related to that option.

Specifically this prevents me from running black on multiple projects in one command. Perhaps this is by design.

To Reproduce

Black version

black, 24.8.0 (compiled: yes)
Python (CPython) 3.10.10

...

flat krakenBOT
#

Description

This CL fixes an inconsistency of when to skip formatting of Jupyter cells with unknown magic methods.

Black correctly skips formatting in this case:

%%unknown_custom_magic

However if the cell started with some empty lines black still tried to format it and failed:



%%unknown_custom_magic

Also if the cell started with a comment black tried to format it:

# Some comment
%%unknown_custom_magic

(This example isn't...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
stable hollow
#

github

azure plank
#

I keep periodically checking for updates on issues I comment on, and the more I read it the more this comment gives me an ai generated smell https://github.com/psf/black/issues/4461#issuecomment-2383074406 if it is ai generated I’m always confused on why. It’s not like they gain anything from making comments on GitHub issues. Are they just too lazy to bother writing a “hey I could fix this” message themselves? So strange.

GitHub

Describe the bug Black configurations are seemingly not taken into account for any paths after the first one passed to CLI - I'm seeing this in particular for "line-length" but have n...

flat krakenBOT
flat krakenBOT
hushed drift
dense jungle
silent knoll
flat krakenBOT
#

The latest version (24.10.0) drops Python 3.8 runtime support via #4452. Error messages and documentation were not updated outside of the changelog.

This creates significant conflicting information between actual requirements and installation instructions, error messages, etc.

Here are a few places (not an exhaustive list) that need updating:

README.md

https://github.com/psf/blac...

carmine coyote
flat krakenBOT
#
# short line is ok
dict1 = {long_name_items, long_name_items, long_name_items, long_name_items}

# long line (more than --line-length) will cause one item per line:
# it looks too high, especially when the collection has many items
# and the last comma cannot be removed
dict2 = {
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
    long_name_items,
...
dense jungle
#

Also looks like the docs didn't update for the 24.10.0 release

carmine coyote
#

idk the intricacies of "rtd", but having "permalinks" is a nice feature 😅 (ofc tags are not permanent, like shas, but oh well ...)

#

Hoping you'd consider it 🙏 (even if black goes strictly forward and is "relatively stable" i.e. not a lot of user-facing breaking chnages)

flat krakenBOT
#

Describe the bug

To Reproduce

Load a python script in VSCode.
Ensure auto save is toggled on.
Make a change to the script where the formatting is such that Black would correct.
Observe file content gets autosaved but the Black formatting is not applied.
Save with Ctrl-S
Observe that the formatting is applied.

Expected behavior

I would expect that when the file gets autosaved, the Black formatting would be applied.

  • Black's version: 2024.2.0
  • OS ...
flat krakenBOT
#

Describe the bug

Error when formatting a folder with multiple files using the command line

To Reproduce

For example:
Create a new folder src and create 2 empty files in src

mkdir src
type nul > ./src/t1.py
type nul > ./src/t2.py
black ./src

The resulting error is:

Traceback (most recent call last):
  File "", line 198, in _run_module_as_main
  File "", line 88, in _run_code
  File "C:\Users\root\AppData\Local\pypoetr...
elder tusk
flat krakenBOT
lethal forge
brisk oxide
#

Sorry to put the message here. I want to do open source in python based projects. Can anyone help me with that. Guide me which is easy and where should I start, or like help me get started.
I really want to be part of this but I don't know where to begin from.

dense jungle
flat krakenBOT
graceful roost
#

does any1 have any like 2d pixel game code made with pygame?

gusty grail
graceful roost
drowsy jolt
flat krakenBOT
#

Description

Hey! First time contributing to the project so please let me know if I'm doing anything wrong here :)

I've implemented changes for the issue described here https://github.com/psf/black/issues/4389

Esentially if we can combine multiple f-strings into a single f-string without breaking other considerations like the intended line length then I attempt to do so. This is done by breaking apart the AST of multiple f-strings into a single f-string node by only keeping the f...

flat krakenBOT
#

Describe the bug

Formatting the code snippet below produces an internal error.

To Reproduce

Format the following code snippet:

foo(
    bar()    # fmt: skip
  + bar()    # fmt: skip
)

The resulting error is:

INTERNAL ERROR: Black 24.10.1.dev3+g9995bff on Python (CPython) 3.12.5 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_vu09qp1g.log

Log:

I...
flat krakenBOT
#

Description

This PR fixes an issue where Jupyter cells containing any magic method and at least 1 empty line at the start or at the end of the cell don't get formatted at all.

This is an example of a cell that doesn't get formatted:



%time
a=1


But if there are no magic methods then formatting works. The following cell:



#No magic methods
a=1


gets correctly reformatted into:

# No magic methods
a = 1

It turns out the proble...

timber comet
#

-a - allow string , -max-string

flat krakenBOT
#

Description

This PR continues work started in #4458 and replaces remaining aliases to built-in types with actual built-in types. I made the update everywhere except in the tests/data subfolder which contains only test cases.

Checklist - did you ...

  • [ ] ~Add an entry in CHANGES.md if necessary?~
  • [x] Add / update tests if necessary?
  • [ ] ~Add new / update outdated documentation?~
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

Discovered in https://github.com/python-trio/trio/pull/3106#discussion_r1794256324, black is parenthesizing context managers for Python 3.9 despite that only officially landing in 3.10.

This isn't actually much of an issue as CPython 3.9 allows it and I assume PyPy does too, but it could technically be an issue and does mess things up with -X oldparser on 3.9.

Checklist - did you ...

  • [x] Add an entry in CHANGES.md if necessary?
  • [x] Add / up...
#

Description

Hey! Trying to contribute for the first time to the project so let me know if I'm missing anything :)

I've implemented changes to address this issue https://github.com/psf/black/issues/2020 where there's some inconsistency around how many lines are added after an import. I've added 2 test cases showing that if there is more than 1 blank line between the import and the next line that it is now being reduced to one. One test case was failing because it had in its expected...

flat krakenBOT
lucid marlin
#

Hello mentors, i want to contribute in your project can you give simple code base issue that i solve i am beginner in open source

flat krakenBOT
flat krakenBOT
#

Describe the bug

The string-processing produces an invalid f-string when joining together two strings where both literals have a debug expression with quotes

f"{10 + len('bar')=}" f'{10 + len("bar")=}'
Cannot parse for target version Python 3.13: 2:30: f"{10 + len('bar')=}{10 + len(\"bar\")=}"

To Reproduce

[Playground](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AESAJJdAD2IimZxl1N_WlkB95OW0C662fyie0CNcYZEC8wQ...

#

Describe the bug

Sorry for another cursed example.

Black changes the " in the second inner f-string expression to '` which changes the program output.

f"{'''test ' '''}" f'{"""other " """}'

Actual output

f"{'''test ' '''}{'''other ' '''}"
#                          ^ note the changed quote 

To Reproduce

Create a file with the above code and run with --unstable with a pre python 312 target.

Or see [this playground](https://bl...

flat krakenBOT
#

Describe the bug

When using unstable, f-string quotes get incorrectly changed if the expression contains a conversion. This changes program behavior. As an example, "" f'{""=!r}' currently formats to f"{''=!r}".

>>> print("" f'{""=!r}')
""=''
>>> print(f"{''=!r}")
''=''

To Reproduce

Format this code

"" f'{""=!r}'

[Playground link](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ACXAFtdAD2IimZxl1N_Wk7-...

azure plank
#

"These should be some easy first issues" I naively thought looking at 4493/4494. "Just adding some basic checks to wherever the f-string formatting happens"
It was, in fact, not easy, nor straightforward. 🫠

flat krakenBOT
azure plank
#

@dense jungle Quick question I can't seem to figure out, is there a way to run only one test? With tox -e py it always has to redownload and rerun everything, which is making fixing this issue take forever.

#

To be specific, run one file inside black/tests/data/cases

dense jungle
#

with -k to filter by names

flat krakenBOT
azure plank
#

Yay first PR opened, I hope I didn't mess anything up 🥴

#

I plan to later do a pr for updating the contributing basics since there were several things that would have been nice to have there, but there is one thing I don't know how to fix. The next pr number link is broken because at some point the ampersand gets escaped, making it invalid. It still goes to the website, just not with the black details autofilled. ```
https://ichard26.github.io/next-pr-number/?owner=psf&amp;name=black

Since the source code has the correct link, ```
https://ichard26.github.io/next-pr-number/?owner=psf&name=black

This is some escaping issue and I have no clue how to fix it.

#

Trying to url-escape the ampersand with %26 also doesn't work, though I don't know why.

flat krakenBOT
#

Hi

January isn't too far off anymore ;), and I was wondering if you already have plans for what preview features you want to stabilize as part of the Black 2025 style guide.

I'm working on Ruff's formatter, and my goal is to align Ruff's preview-style promotions with Black's to have a unified 2025 Python style guide (at least style guides that are very close).

New Black preview styles that you implemented during 2024 that I'm aware of (that aren't bug fixes):

  • [`remove_redundant_...
dense jungle
#

Thanks for your contribution, I'm about to start reviewing your PR. Not sure what's going on with the &, maybe it's a bug in myst-parser?