#black-formatter

1 messages Β· Page 6 of 1

analog anvil
#

https://i.imgur.com/ejli3Vm.png

Just had this pop up in my neovim when trying to run :Black, its been working great until recently. I never had this message before. Currently on python 3.12 and nightly neovim

flat krakenBOT
neon loom
#

Am I blind - is there any docs on the easiest way to build a compiled black wheel? I'm trying to change the Dockerfile to compile by default. Should
hatch build --ext
Get me a wheel?

crl-m1:black cooper$ /tmp/tb/bin/hatch build --ext
[wheel]

I'm a hatch / mypyc n00b

#

Once i get a compiled wheel I plan to install it to /opt/venv which we copy to the published docker image

#

re-reads ichard's blog post

#

Damn, it's all using setup.py ... not gonna helps me I think

#

Ok - Got a non compile - Now to workout how to make it try to compile

crl-m1:black cooper$ /tmp/tb/bin/hatch -v build -t wheel
[wheel]
Building `wheel` version `standard`
dist/black-23.10.1.dev1+g882d879.d20231022-py3-none-any.whl
neon loom
neon loom
#

Got there, was just missing the env var to compile πŸ™‚

#

ofek helped me ❀️

zinc shell
#

Hey, mmm I just had a very bad experience asking for help in #ot0-fear-of-python ...

I am lookin for help as I am trying to learn..

recently i installed a program called "X-Osint" from github and it was unstalled using sudo
does anyone know how to uninstall it?
i installed it in kali linux on windows 11
already tried sudo apt-get remove xosint
but it says "E: Unable to locate package xosint"

#

can anyone help me here?

#

i just want to unsintall it as it is of no use

neon loom
#

I don't think is the right channel to ask for help on this friend.

neon loom
#

Sorry was in meetings and missed you merged. Thanks πŸ˜„

neon loom
#

Do we want to get a hotfix out today for the github action failure?

dense jungle
#

yeah probably. We've accumulated a few other improvements too

neon loom
#

If you want I can drive it (have to read docs to remember how :D)

#

Happy to try start the diff to make changelog is up to date etc.

dense jungle
neon loom
#

Ok - I'll cut one soon - Got side tracked on $job work

#

Anything else we want merged or you're happy with where we are?

dense jungle
neon loom
#

I guess we should open an issue for Windows Doc builds failing

neon loom
#

I feel we should add the new release block after release so we don't pollute pypi.org + tagged commit with it :\

#

I disagreed with it in the docs πŸ™‚

dense jungle
neon loom
#

Yeah, I'll do a diff and change the docs right after release

#

@dense jungle Would you accept a PR adding a shell script to run that sed -i s/$OLD_REL/$NEW_REL/g for the files we have version strings in? I dislike editing those strings πŸ™‚

dense jungle
neon loom
#

I might write in python so it works for our lovely Windows people πŸ™‚

flat krakenBOT
dense jungle
neon loom
#

Yeah, I'll do that too. python I can write unittests too cause I don't trust myself

#

The compile build takes a long long time in docker

#

Cause we compile x86 and then cross compile aarch64

#

I should see if I can get them to go in parallel like ichard does for our wheel building

flat krakenBOT
neon loom
#

^^ Would love anyone with killer GitHub actions CI skills here to PR plz πŸ˜„

#

I am stuck in the Meta world, so my GitHub skills are limited

#

docker CI == 10x runtime regression - 5 mins to 50 mins ... lol 😦

dense jungle
neon loom
#

O yeah, will be a ~2x for many users for free

#

I'm just impatient and dislike slow CI

neon loom
#

Ok - all built - Cutting release

flat krakenBOT
neon loom
#

Our docs should auto build etc. right?

#

Seems CI will move the stable branch and then a docs build will kick off?

dense jungle
#

thanks for doing the release!

neon loom
#

No worries, good to do it after a long break πŸ˜„

neon loom
#

Hmm, seems the release breaks black-pre-commit-mirror

#

It needs some cronjob?

#

Wonder if we can click run now or something and then think of a better way

dense jungle
neon loom
#

Did you just retry it?

#

Or click this?

dense jungle
#

seems like it succeeded

neon loom
#

Yeah seemed to work

flat krakenBOT
neon loom
#

Does psf org have access to larger runners? cc: @solid adder ... Would like to move the docker ci there if we can ...

solid adder
neon loom
#

Thanks - No biggy if we don't

#

I just regressed the docker build 10x moving it to compile black (5 mins to 50 mins) - I was surprised it was that much

We should be able to ~1/2 that doing the aarch64 + x86_64 builds in parallel ... Just gotta workout how to do that

flat krakenBOT
neon loom
#

Anyone know how to install git on a Windows Github Action runner? If not, I'm gonna remove it from the CI for release tool CI for now and open a issue for someone to help with it ... Cause I haz 0 windows skills

#

I'll try google it now

flat krakenBOT
#
sth

Describe the bug

If I have as file named somefile in the root of the project and I want to include it with --include, traditionally the appropriate regex would contain a leading slash:

black --include '^/somefile$' ...

In #3846 this changed, now the leading slash prevents the file from being matched. Instead --include '^somefile$' is required.
The related exclude regexes still need the leading slash.

The cause are the path processing changes in #3846. Slashes are ...

neon loom
#

Damn, sorry about the noise people subscribed. It looks like I'm gonna have to move back to python3.12 release_test.py and add print statements to see why we're failing with more detail - coverage seems to hide everything but the last exception ... but it seems I'm not getting git tag output, but I felt I had mocked git running out ...

clever peak
#

out of curiosity, do yall use mypy's stubgen at all?

dense jungle
flat krakenBOT
#

Describe the bug

The following snippet blocks git commits:

    # Get the counts and the bin centres
    counts, bin_centres = np.take(res, 0, axis=axis), np.take(res, 1, axis=axis)
    sel = [0] * len(np.shape(bin_centres))
    sel[axis] = None
    bin_centres = bin_centres[*sel].flatten() # <---- Error!

with error

error: cannot format model_plots/data_ops.py: Cannot parse: 462:30:     bin_centres = bin_centres[*sel].flatten()
  • Black's ...
neon loom
#

Some nice passer-byer informed me! Makes sense. I didn’t realize that limited tags.

flat krakenBOT
flat krakenBOT
#

Description

This PR contains some refactoring to comments.py, as the code was not the cleanest and comments/naming were not up to date. This also fixes bugs with using multiple fmt: skip pragmas inside a single block, originally reported here.
Due to the refactoring, this PR is in small commits, so it's easier to review the changes piece by piece.

Checklist - did you ...

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

Trying to get a compiled black on 3.12 (the wheel on PyPI is not)

I'm building from tag 23.10.1 on Python 3.12.0 with the following:

HATCH_BUILD_HOOKS_ENABLE=1 MYPYC_OPT_LEVEL=3 MYPYC_DEBUG_LEVEL=0 CC=clang AIOHTTP_NO_EXTENSIONS=1 pip install -vv .

The build succeeds but the app crashes

$ .venv/bin/black
Traceback (most recent call last):
  File ".../.venv/bin/black", line 5, in 
    from black import patched_main
  File "src/black/__init__.py", line 64, in 
    from bla...
flat krakenBOT
#

On macOS Ventura 13.6 on Apple Silicon, pip selects the universal pure Python wheel when installing Black 23.10.1:

❯ pip install black==23.10.1 --only-binary :all: --no-cache
Collecting black==23.10.1
  Downloading black-23.10.1-py3-none-any.whl.metadata (66 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 66.0/66.0 kB 1.2 MB/s eta 0:00:00
Requirement already satisfied: click>=8.0.0 in /Users/ambv/.virtualenvs/aiotone11/lib/python3.11/site-packages (from black==23.10.1) (8.1.6)
...
#

Describe the bug

On https://pypi.org/project/black/23.9.1/#files I can see a black-23.9.1-cp311-cp311-macosx_10_16_universal2.whl.

On https://pypi.org/project/black/23.10.1/#files I only see black-23.10.1-cp311-cp311-macosx_10_16_arm64.whl.

According to python -c 'from packaging.tags import platform_tags as t; import pprint; pprint.pprint(list(t()))' my platform tags are:

['macosx_14_0_arm64',
 'macosx_14_0_universal2',
 'macosx_13_0_arm64',
 'macosx_13_0...
flat krakenBOT
#

Describe the bug

Our CI needs [d] extra install which brings in aiohttp. Due to this we don't work in 3.12

aiohtp are working on their 3.12 release: https://github.com/aio-libs/aiohttp/issues/7675

  • They have found bugs due to things being fixed in 3.12 ans a regression in one of their deps

To Reproduce

Install black[d] in python 3.12

Expected behavior

We install and CI passes

Environment

  • Black's version: main
  • OS and Python version: Any OS + 3.12
flat krakenBOT
flat krakenBOT
flat krakenBOT
#
sth

Description

This adjusts exclusion checking for command line parameters the same way as #3846 did for other files. Specifically, --force-exclude is now checked before symlink resolution. This way symlink handling is consistent between command line parameters and other collected files.

Fixes #3826.

Checklist - did you ...

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

Hi! I'm working on the ruff formatter, a fast black compatible formatter.

There are a lot of impactful style improvements that are currently in preview style, which we are working to support, currently also gated behind a --preview flag. Do you already have a rough date in mind when you want to promote the preview style to stable, and do you know if you'll promote all rules or keep some of them in preview for another year (e.g. the new string wrapping...

neon loom
#

So I'm a little lost, what do we need to do to make our MacOSX cp11 wheels happy? Are we waiting for fiixes or we have to make some >= 11_0 version? I feel threads contradict ...

#

I'd be happy to fuck a 23.10.2 or at least have it ready for 23.11.0

#

Do we want macos-max-compat?

flat krakenBOT
dense jungle
#

why are there so many typo fix PRs lately

#

is that hacktoberfest?

gusty grail
#

Maybe
But that change is kinda specific

#

Like you'd have to be actually interested in reading that doc

dense jungle
#

I guess good that people are reading the docs, in that case πŸ™‚

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Thanks! I haven't reviewed this in detail, but it looks promising. Two points:

  • This PR also makes us format code inside f-strings. That's a good thing, but we should do it only in the preview style, as otherwise we'd break our stability guarantee.
  • I don't like that the style currently puts line breaks inside the f-string placeholders:
% black --line-length=10 -c 'f"aaaaa{xxxx}aaa"'
f"aaaaa{
    xxxx
}aaa"

That looks weird and it's not how a human would split the string.

elder tusk
flat krakenBOT
gusty grail
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

I noticed what appears to be inconsistent formatting when comparing black's output (v23.10.1) to ruff's new formatter (v0.1.3), as I reported to ruff and can demonstrate here:

x = (
    very_long_function_name_with_many_arguments(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000).f()
    # Comment
    .g()
)
y = (
    very_long_function_name_with_many_arguments(100, 200, 300, 400, 500, 600, 700, 800, ...
flat krakenBOT
#

Description

trendshift.io captures the daily Github Trending data and generates a nice badge based on the highest achieved rank. This PR embeds the badge in the readme file, and hopefully, It helps to motivate contributors and attract more users.

Checklist - did you ...

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

I wasn't sure if I should submit a style or bug report for this (or should it be a question?). I'm sorry if I picked the wrong template.

Black implements a neat little optimization for constants and namves to avoid wrapping them in parentheses when the parenthesized expression exceeds the line length.

In the following code, Black omits parenthesizing the "exceeds parenthesized" cases because the code exceeds the line length when adding and when omitting the optional parentheses, which...

#

Black reformats the contents of triple quoted byte strings in docstring position, even though those are not docstrings, causing a crash due to AST changes:

def f():
    b""" a"""
INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_rb9415ox.log

--- src
+++ dst
@@ -18,11 +18,11 @@
           value=
             Constant(
               ...
flat krakenBOT
flat krakenBOT
half meteor
#

Hey Black maintainers, I will finally have some time for https://github.com/psf/black/issues/1352#issuecomment-1379257052
Are you still interested in this? Since this will be a big change, I hope to get buy-in before I start sending PRs.
It's currently implemented in Pyink via this interface: https://github.com/google/pyink/blob/5fd9550dc109ed26801b5999d356c56ad6bb4eb1/src/pyink/__init__.py#L311-L320
The majority of the logic is in this convert_unchanged_lines function: https://github.com/google/pyink/blob/5fd9550dc109ed26801b5999d356c56ad6bb4eb1/src/pyink/__init__.py#L1221, which is similar to how fmt: off/on is implemented.

late dewBOT
#

src/pyink/__init__.py lines 311 to 320

@click.option(
    "--pyink-lines",
    multiple=True,
    metavar="START-END",
    help=(
        'Range of lines to format. Must be specified as "START-END", index is'
        " 1-based and inclusive on both ends."
    ),
    default=None,
)```
`src/pyink/__init__.py` line 1221
```py
ink.convert_unchanged_lines(src_node, lines)```
dense jungle
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

From this issue.
The new string processing can split an f-string to multiple lines. Because we run two passes on the source, we can end up with cases where

f'Some long string foobar={foo["bar"]}'

gets transformed on the first pass into

"Some long string"
f' foobar={foo["bar"]}'

Now we don't have knowledge of the original quote types, so this will be processed in the second pass into

"Some ...
flat krakenBOT
#

I believe this is related to the improved line breaks preview-style.

Examples in the current Black style

The following is blacked code using preview styles (copied from the playground).

aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  # 11111111111111111111
a["a"] = (
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa  # 11111111111111111111
)
a = (
    aa
) = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
flat krakenBOT
#

Describe the bug

The "Improved line breaks" preview style should break the value before the target according to the preview style documentation. This is true for the first target, but doesn't seem to be the case when using assignments with multiple targets:

To Reproduce

a["a"] = b["b"] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Gets formatted as

a["a"] = b[
    "b"
] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
flat krakenBOT
flat krakenBOT
flat krakenBOT
neon loom
#

Damn, black is active at the moment

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

These changes are mostly a no-op. The logic in these two functions is quite similar. In the next PR I make, I'll fix https://github.com/psf/black/issues/3826 by making the logic in get_sources match the newer logic in gen_python_files. This PR separates out non-functional changes from that functional change.

Can be reviewed commit by commit. The last commit is probably the most notable; it would change an AssertionError into whatever the underlying error is.

flat krakenBOT
young sand
flat krakenBOT
normal solar
#

Hello

mint barn
#

self bot

tight hollow
#

"D:\Program Files (x86)\Anaconda\Scripts\black.exe" C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb
I want to format "Lesson 4.ipynb". Obviously, there's a blank space in the middle. So how can I format this file without rename. BTW, it can be opened as start "Lesson 4.ipynb" in cmd. But I can't "C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb" in black. I would appreciate it if anyone could help me!

dense jungle
tight hollow
#

PS C:\Users\sasa\Desktop\Lesson 3> "D:\Program Files (x86)\Anaconda\Scripts\black.exe" "C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb"

  • ... da\Scripts\black.exe" "C:\Users\sasa\Desktop\Lesson_4\Lesson 4.i
    pynb"
  •                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    
β€œ"C:\Users\sasa\Desktop\Lesson_4\Lesson 4  
.ipynb"”。
    + CategoryInfo          : ParserError: (:) [], ParentContainsErro  
   rRecordException
    + FullyQualifiedErrorId : UnexpectedToken
I already tried. But it didn't work.
dense jungle
#

maybe single quotes instead? for what it's worth that error doesn't come from Black

tight hollow
#

PS C:\Users\sasa\Desktop\Lesson 3> "D:\Program Files (x86)\Anaconda\Scripts\black.exe" 'C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb'

  • ... da\Scripts\black.exe" 'C:\Users\sasa\Desktop\Lesson_4\Lesson 4.i
    pynb'
  •                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    
β€œ'C:\Users\sasa\Desktop\Lesson_4\Lesson 4  
.ipynb'”。
    + CategoryInfo          : ParserError: (:) [], ParentContainsErro  
   rRecordException
    + FullyQualifiedErrorId : UnexpectedToken
it still can't work
#

Cannot run program "D:\Program Files (x86)\Anaconda\Scripts\black.exe" (in directory "C:\Users\sasa\Desktop\Lesson 3 "): CreateProcess error=193, %1 is not a valid Win32 application. what happens with this, at first time, it can be formatted

elder tusk
flat krakenBOT
#

Describe the bug
black reports an internal error when formatting a specific file.

error: cannot format /home/nicpa/codes/sisl/src/sisl_toolbox/siesta/minimizer/_metric_siesta.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__3mh1ucd.log

To Reproduce

  1. Download [this file](https://github.com/zerothi/sisl/blob/5a63302b57fcb38d7460...
flat krakenBOT
flat krakenBOT
echo pebble
#

Hello

I am trying to use black in a gitlab ci

black:
  stage: linting
  image: registry.gitlab.com/mafda/python-linting
  script:
    - python -m black . --check --verbose --diff --color

But it says : Error: No such option: --color Did you mean --code?
Anyone has any idea, please?

dense jungle
echo pebble
dense jungle
#

seems like it hardcodes black==19.10b0

#

which just had its fourth birthday

#

that suggests it's not a well-maintained project

echo pebble
#

i understand. Thanks

flat krakenBOT
flat krakenBOT
#

Description

This allows the use of form feeds in code formatted with Black. Addresses #1100

The short form of the motivation is that form feeds represent a page break, and
are used by some editors to organize code. Issue #1100 has a little more discussion.

This enforces a couple rules: a form feed is only allowed at the module level,
on a line by itself. Multiple form feeds in the same prefix are merged with each
other. Any form feed is moved to the last empty line of...

flat krakenBOT
flat krakenBOT
#

Simplify the has_magic_trailing_comma logic (it will make #3918 a bit easier to implement).

The second if cannot be true at its execution point, because it is already covered by the first if. The condition
comma.parent.type == syms.subscriptlist always holds if closing.parent.type == syms.trailer holds, because subscriptlist only appears inside trailer in the grammar:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: (subscript|star_expr) ...
flat krakenBOT
flat krakenBOT
#

Description

Fixes #3850 .

Previously Black doesn't recognize case block as one of the syntax blocks need to be wrapped with invisible parentheses, and hence will also not be splitting the case blocks into multiple lines even when it's too long.

Now with (invisible) parentheses correctly wrapped around case blocks, the lines are able to be splitted into multiple lines when needed, this also allows the trailing comma rules to be enabled for case blocks. Unit test `pattern_...

flat krakenBOT
#

In IPython notebook, trailing ; has a specific effect of suppressing the last output: https://ipython.org/ipython-doc/dev/interactive/tips.html#suppress-output

Other Colab extensions like https://github.com/google/etils also use ; to pretty display the line (as alias of the verbose IPython.display.display): https://etils.readthedocs.io/en/latest/ecolab.html#pretty-display-with-trailing

Colab/IPython notebook are meant for fast iteration. As such, those hack are very useful for fas...

flat krakenBOT
#

Describe the bug

Inside a list, a comment followed by a single line with division operator causes additional lines breaks before each division operator.

To Reproduce

For example, take this code:

import pathlib

foobar = [
    # comment
    pathlib.Path("foo") / "bar" / "baz",
]

fizzbuzz = [
    # comment
    23 / 7
]

And run black on it with the default config.

The resulting formatted code is:

import pathlib

foobarb...
flat krakenBOT
#

Using macOS:

$ black --version
black, 23.10.1 (compiled: yes)
Python (CPython) 3.10.12

Take this code:

"""This is a test case, note blank lines next."""
def go():
    print("Do stuff!")
go()

And run this:

$ black --diff blanks.py 
--- blanks.py	2023-11-06 18:04:21.775563+00:00
+++ blanks.py	2023-11-06 18:04:37.405865+00:00
@@ -1,4 +1,8 @@
 """This is a test case, note blank lines next."""
+
+
 def go():
     print("Do stuff!")
+
+...
flat krakenBOT
dense jungle
#

we should do a release in the next few days after the current crop of PRs is merged

flat krakenBOT
flat krakenBOT
#

Thanks for your contribution. Technically this looks good, but I'm not sure support for form feeds is worth the additional complexity. There hasn't been a lot of interest in the issue (only a few people commented over four years), and it was noted that several other languages either don't support formfeeds at all or use formatters that remove them. So I think Black might be doing the right thing in consistently removing a character that is rarely used and will most likely confuse most users i...

flat krakenBOT
#

Hello! :)

Description

I noticed a typo in the docs.
The flake8-bugbear error code was mistyped as "E950" instead of "B950".

Checklist - did you ...

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

(I suppose none of the above applies...)

half meteor
#

The diff-shades preview checker seems to be failing on the CI?

dense jungle
flat krakenBOT
dense jungle
#

the docker build on main has been running for 47 minutes... 😱

flat krakenBOT
flat krakenBOT
dense rune
dense jungle
flat krakenBOT
#

Describe the bug

I can't get the recently-merged --line-ranges command line option to work at all. It either produces incorrect results, or produces an internal error (details below).

To Reproduce

Five lines of input causes an internal error

$ cat unformatted.py 
print ( "format me" )
print ( "format me" )
print ( "format me" )
print ( "format me" )
print ( "format me" )
$ black --line-ranges=2-3 unformatted.py 
error: cannot format unformatted.py: INTERN...
half meteor
# flat kraken

This is indeed caused by the diffing algorithm in adjusted_lines.
I'm not sure this is really fixable, since you should always be able to construct an edge case to make the diffing algorithm produce an undesired output.

late dewBOT
#

src/black/__init__.py line 1472

lines = adjusted_lines(lines, src, dst)```
flat krakenBOT
flat krakenBOT
#

Description

When performing a second formatting pass with --line-ranges, we can't simply use the original lines specified by the user.

For example, unformatted:

def restrict_to_this_line(arg1,
  arg2,
  arg3):
    print  ( "This should not be formatted." )
    print  ( "This should not be formatted." )

If we let it format lines 1-3, after the first pass it becomes:

def restrict_to_this_line(arg1, arg2, arg3):
    print  ( "This sh...
flat krakenBOT
#
  • With aiohttp >= 3.9.0b1 we can now install all dependencies with 3.12
    • Will wait for an official release before merging
  • Add actions to run 3.12

Test:

  • python3.12 -m venv /tmp/tb --upgrade-deps
  • /tmp/tb/bin/pip install tox
  • /tmp/tb/bin/pip install .[d]
  • /tmp/tb/bin/tox -e py312
  py312: OK (37.61=setup[3.98]+cmd[3.83,0.36,19.54,6.46,3.00,0.44] seconds)
  congratulations :) (37.63 seconds)

Description

Checklist - did you ...

-...

neon loom
#

We close ...

flat krakenBOT
#
foo(  # type:ignore
    [  # type:ignore
        a
    ]
)
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_qaa1dff6.log

--- src
+++ dst
@@ -29,8 +29,6 @@
         )  # /Call
     )  # /Expr
   type_ignores=
     TypeIgnore(
     )  # /TypeIgnore
-    TypeIgnore(
-    )  # /TypeIgnore
 )  # /Module
\ No newline at end of file

[pl...

flat krakenBOT
half meteor
# dense jungle yes, that's been happening intermittently. I haven't been able to find useful lo...

I tried diff-shades with the preview style locally a couple of times and it has been fine.

Looking at a recent run: https://github.com/psf/black/actions/runs/6814056685?pr=4037

The hosted runner: GitHub Actions 7 lost communication with the server. Anything in your workflow that terminates the runner process, starves it for CPU/Memory, or blocks its network access can cause this error.

Maybe it's using too much CPU or memory?

GitHub

The uncompromising Python code formatter. Contribute to psf/black development by creating an account on GitHub.

dense jungle
half meteor
elder tusk
#

maybe we have a perf regression?

half meteor
flat krakenBOT
#

This implement the proposal in #3918.

I wasn't sure if this needs to go as a preview option; it shouldn't affect already formatted code (so adheres to the Stability Policy), but it does change how unformatted input is formatted.

Split to multiple commits to make reviewing a bit easier. Can be squashed to a single commit. The actual meaningful change is the last commit.

I've used opening.lineno != closing.lineno as an easy way to detect "multiline". I think it's correct and simple b...

flat krakenBOT
#

Description

Pragma comments have similar semantics as # type: ignore, so they should be treated similarly: lines marked with them are fine to merge (this generally extends the scope of the suppression/pragma) but not OK to split.

Checklist - did you ...

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

Try ticking "skip temporary sanity checks" in the settings (bottom left)

earnest sequoia
#

yep, but why does that fail on the playground when it works locally?

austere lava
#

Because the playground uses a runtime older than 3.10

flat krakenBOT
#

Describe the bug

If a long named parameter expression is passed to a function call, black exceeds the line length limit. Adding parentheses fixes the issue, but it feels like Black should do that automatically.

To Reproduce

foo(
    this_is_a_very_looooooooooooooong_parameter_name=some_very_loooooooooooooooooong_variable_name
)

Expected output

foo(
    this_is_a_very_looooooooooooooong_parameter_name=(
        some_very_loooooooooooooo...
upbeat escarp
#

hi, this is a general question. is black supposed to automatically fix your code. I have the settings shown and can see on save it triggers, but it only highlights the errors instead of auto fixing them. I am on ubuntu wsl2 with black installed as a vscode extension (and in my venv as a sanity)

  "editor.formatOnSave": true,
  "python.formatting.provider": "black",
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }
}
bright glacier
#

Black doesn't flag any errors. You must have a linter or type checker installed, too. Perhaps flake8 or ruff or mypy?

#

Black only handles code formatting so while it could probably address many code formatting lint errors that flake8 (for example) would raise, that's just a happy side-effect :)

upbeat escarp
#

i have flake8, i was recommended to add on googling, do i have to remove it to get the auto-formatting of my code to work. i just want for example re sult = x**2 to be auto corrected on save

bright glacier
#

black doesn't fix errors

#

and yes, it does need syntactically valid code or else it will probably fail to format

upbeat escarp
bright glacier
#

I'm confused. That's what black is supposed to do (assuming VSCode is configured to call it automatically on save)

#

Black is not a linter. It merely modifies your code stylistically, adjusting indentation, spacing, line breaks, etc.

#

What code are you trying to format?

upbeat escarp
#

ah i see. so in my example re sult = x**2, because the variable is not valid, black wont format it.

But for bad styled objects like x = {'a': 38, 'b': 42, 'c': 900 } it will fix

bright glacier
#

badly formatted

bright glacier
#

It needs to be able to parse (understand the structure of your code) to be able to format.

upbeat escarp
#

ah i understand. is there some other addon that does what i want to achieve

#

parse and format

bright glacier
#

that's what black does

#

are you looking for something that fixes syntax errors?

upbeat escarp
#

yes

bright glacier
#

I wouldn't be surprised if they exist, but I would strongly recommend learning to resolve them by hand instead. Such tools probably wouldn't be particularly reliable.

upbeat escarp
#

i see, thank you for clarifying the difference/expectation

bright glacier
#

The lines are becoming more and more blurred. Ruff, a hypermodern Python linter does have some autofixing functionality for its lint rules.

#

I doubt it can handle syntax errors, but it can fix certain lint violations at least.

young sand
#

But I personally think of that as a bug rather than a feature πŸ˜†

flat krakenBOT
#

Description

This previous change broke support for versions of pre-commit earlier than 3.2.0.

As far as I can tell, there's no reason not to leave these as commit, merge-commit and push for now. Eventually they will need to be updated, but the current version of pre-commit supports both sets of values.

Checklist - did you ...

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

See issue for 2023 here: https://github.com/psf/black/issues/3407

Here's what this issue is:

  • I've listed all the features we have enabled under --preview
  • I've listed them in descending order of how controversial I think they are
  • I've also drawn a dividing line; past "uncontroversial" is where I feel we don't really need to think twice about it
  • I've listed the number of digits in the diff-shade lines changed count and linked original PR
  • I tried to list any open issues next ...
flat krakenBOT
#

Background:


tldr; the 2023 stable style strips newlines after code block opens. This h...

neon loom
#

I won't die on a hill, but this makes me sad - One of my most hated things about rust formatting.

lament crow
#

While I like this formatting visually, it's not at all what I'd expect Black style to look like based on how Black style looked in the past

#

I know that that's why the changes to the style are only made once a year but it's still quite significantly different from what existing users (including me) might expect

neon loom
#

Yeah, when we started it, since indentation is so important to python, we wanted to make it cleaer everywhere and never wanted to optimize for vertical white space etc.

#

I find this much harder to easily read and pickup the logic

#

Now I admit I'm 200% bias as I've been reading python code in black style before black existed (as ambv, myself and other facebookers decided the style on whiteboards @ work)

half meteor
#

You still have a choice to use the magic trailing comma case by case here to get the previous behavior

neon loom
#

O do I; so we now respect the last trailing comma more accurately?

#

Side note: I wish we never did the magic trailing comma ... Was meant to be a consistent style ... Now, even limited as much as we have, the black style is quite flexible

half meteor
#

For this particular case, yes.

#

For our story we have a large developer base, and having some flexibility like this played a key role to adopt the formatter while keeping most of them happy.

flat krakenBOT
#

Describe the bug

To Reproduce

For example, take this code:

this = "code"

And run it with these arguments:

$ black file.py --target-version py39

The resulting error is:

cannot format file.py: INTERNAL ERROR: ...

Expected behavior

Environment

  • Black's version:
  • OS and Python version:

Additional context

flat krakenBOT
#

File can not be formatted

from datetime import datetime
created = 1699960500
dt = datetime.fromtimestamp(created)
a = "hello"
n = "world"
print(f"{a}. {n} ({dt.strftime("%Y-%m-%d-%H:%M:%S")})")

And run it with these arguments:

$ black file.py

The resulting error is:

error: cannot format file.py:
Cannot parse: 9:35: print(f"{a}. {n} ({dt.strftime("%Y-%m-%d-%H:%M:%S")})")

Expected behavior

Passes black or makes correction.
Perhaps...

flat krakenBOT
#

Description

This PR improves the type hints for black.concurrency.cancel, which are currently imperfect.

The function is annotated to say that it expects an iterable of asyncio.Tasks. However, at the only place where cancel is (indirectly) "called", it is "passed" an object (pending) that can only be inferred by a type checker to be an iterable of asyncio.Futures (asyncio.Task is a subclass of asyncio.Future):

https://github.com/psf/black/blob/58f31a70efe6509ce8213a...

elder tusk
#

also for folks who dislike hug_parens feature, i'm curious how you feel about multiline_string_handling feature

gusty grail
#

!pban 1174251412641828878 30d Looks like you're only here to advertise. We're not an ad-board.

late dewBOT
#

:incoming_envelope: :ok_hand: applied ban to @tawny palm until <t:1702630387:f> (1 month).

balmy siren
#

i am facing an issue where I have to keep single quotes as practice instead of double quotes,
dependencies = [
('slack_automation', '0001_initial'),
("slack_automation", "0001_initial"),

#

but when i use "black ." it changes it to double quotes

dense jungle
balmy siren
#

but if i have already have the code in double quotes can this command change it back to single quotes?

dense jungle
#

no

balmy siren
#

this cmd is giving an error, black --skip-string-normalization

#

black --skip-string-normalization
Traceback (most recent call last):
File "<frozen runpy>", line 198, in run_module_as_main
File "<frozen runpy>", line 88, in run_code
File "C:\Work\workx-backend\venv\scripts\black.exe_main
.py", line 4, in <module>
File "C:\Work\workx-backend\venv\Lib\site-packages\click_init
.py", line 7, in <module>
from .core import Argument as Argument
File "C:\Work\workx-backend\venv\Lib\site-packages\click\core.py", line 615
rv = f'{' '.join(parent_command_path)} {rv}'

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

This PR bumps the pinned version of mypy to 1.7.0. Since mypy 1.7.0 includes https://github.com/python/mypy/commit/940fceb59a55513913c3c9c1eaf89a7f5ee774d6, this should unblock us from creating mypyc-compiled wheels for Python 3.12 (though I don't do that here; it's deferred to a followup PR).

Checklist - did you ...

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

Description

If you run pre-commit run -a flake8 o Black with a Python 3.12 environment, it fails:

(.venv) C:\Users\alexw\coding\black>pre-commit run -a flake8
[INFO] Initializing environment for https://github.com/pre-commit/mirrors-mypy.
[INFO] Initializing environment for https://github.com/pre-commit/mirrors-mypy:types-PyYAML,tomli >= 0.2.6, = 8.1.0, != 8.1.4, != 8.1.5,packaging >= 22.0,platformdirs >= 2.1.0,pytest,hypothesis,aiohttp >= 3.7.4,types-commonmark,urllib3...
flat krakenBOT
#

Description

aiohttp==3.9.0 fails to import if you're using PyPy on Windows: see https://github.com/aio-libs/aiohttp/issues/7848. This is currently causing our Windows/PyPy CI job to fail on every PR. We're using PyPy3.8 in CI, but bumping to PyPy3.9 in CI doesn't fix the problem: see the failing CI on the latest commit of #4035.

This PR just blocks aiohttp==3.9.0 from being installed in CI, to make things green again.

Checklist - did you ...

  • [x] Add an entry ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Currently, Black performs two formatting passes, and also performs an extra formatting pass for stability check in --safe mode.

When performing a second formatting pass with --line-ranges, we can't simply use the original lines specified by the user. For example, unformatted:

def restrict_to_this_line(arg1,
  arg2,
  arg3):
    print  ( "This should not be formatted." )
    print  ( "This should not be formatted." )

If we let it format lines 1-3, after the...

flat krakenBOT
half meteor
#

I took another look at possible preview style regressions.
I ran diff-shades at each recent commit on my M1 Mac Mini, here are the results: https://paste.pythondiscord.com/FAVQ

It did take noticeably longer after https://github.com/psf/black/commit/1d4c31aa589dc0c8633af7531f8cc09192917b38 and https://github.com/psf/black/commit/b7717c3f1e73d6b847e2534a2cebbb657b96caf8

The reason it takes longer is not that the newly added code has a perf issue. It's because more files will be reformatted, so more files will make Black perform a second formatting pass, doubling the time for affected files.

GitHub

Co-authored-by: jpy-git
Co-authored-by: Jelle Zijlstra

flat krakenBOT
#

Describe the bug

Python 3.12 introduced some updates to the f-string grammar (see PEP 701), includingβ€”among other thingsβ€”quote reuse: strings nested within an f-string can now use the same quote character as the f-string itself. Black doesn't recognize this, inadvertently changing the semantics of some programs containing f-strings.

To Reproduce

For example, take this code:

# file.py
from urllib.parse import quote


dest ...
neon loom
#

Damn, splitting the builds for docker did nothing sadly + broke it as they tag seperately so we don't get same arch builds with same tags ... https://hub.docker.com/r/pyfound/black/tags

Times were:

  • amd64: ~4 mins
  • arm64: ~35 mins

Old flow was ~30-40 mins in total ... so we really won nothing here sadly ...

I'll put up a PR reverting it ...

  • Potentially broke latest + latest_non_release tag users ... Once we revert and merge to main it will build together again and tag both architecture versions together again ...
flat krakenBOT
neon loom
#

Also see while I watch building:

#21 62.12 [wheel]
#21 62.76 /root/.local/share/hatch/env/virtual/black/VsnhxLU2/black-build/lib/python3.12/site-packages/setuptools_scm/git.py:163: UserWarning: "/src" is shallow and may cause errors
#21 62.76   warnings.warn(f'"{wd.path}" is shallow and may cause errors')

So if we ever see weirdness ... we need to change to full checkouts in our build workflows ...

flat krakenBOT
flat krakenBOT
#

When running:

black -l 80 --check --diff .

On a system configured for FIPS, the command fails with:

Traceback (most recent call last):
  File "/usr/local/bin/black", line 8, in 
    sys.exit(patched_main())
  File "src/black/__init__.py", line 1504, in patched_main
  File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 1157, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/click/core.py", line 1078, in main...
flat krakenBOT
#

On Black 23.11.0:

% black -v --line-length 1 -c 'def f() -> tuple[int, int]: pass' --preview
def f() -> tuple[int, int]: pass
Traceback (most recent call last):
  File "src/black/__init__.py", line 1444, in assert_equivalent
  File "src/black/parsing.py", line 140, in parse_ast
SyntaxError: expected ':' (, line 1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "src/black/__init__.py", line 782, in reformat_code...
#

I found this change in our test suite while trying to stabilize the preview style:

 match command.split():
     case ["north"] | ["go", "north"]:
         current_room = current_room.neighbor("north")
-    case ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]:
-        ...  # Code for picking up the given object
+    case (
+        ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]
+    ): ...  # Code for picking up the given object

This is from the `dumm...

#

See #4042.

I enabled almost all current preview features based on the discussion in #4042.

I didn't yet:

  • Fix the entire test suite. Partly because I found a few bugs while doing this (#4062, #4063), partly because I was lazy.
  • Remove # flags: --preview from test cases that no longer need it

However, this should be enough to get useful diff-shades feedback.

flat krakenBOT
#

Describe the bug

When the pre-commit hook is installed and I commit, I get:

An error has occurred: InvalidManifestError: 
==> File /home/martin/.cache/pre-commit/repolc31_gpb/.pre-commit-hooks.yaml
==> At Hook(id='black')
==> At key: stages
==> At index 0
=====> Expected one of commit, commit-msg, manual, merge-commit, post-checkout, post-commit, post-merge, post-rewrite, prepare-commit-msg, push but got: 'pre-commit'

To Reproduce

$ python --version...
flat krakenBOT
late dewBOT
#

:incoming_envelope: :ok_hand: applied timeout to @warm burrow until <t:1700599475:f> (10 minutes) (reason: emoji spam - sent 50 emojis).

The <@&831776746206265384> have been alerted for review.

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Context:

def func(a: int, b: int) -> int:
    return a + b 

def func(
    a: int,
    b: int,
) -> int:
    return a + b

python 3.12 new feature:

glacial harness
#

Hi!
I was wondering, will this error be fixed in the next black release?

d = { "foo": "test" }
text1 = f"this is just a {d["foo"]}" # Black fails parsing that despite it being correct in Python 3.12
text2 = f"this is just a {d['foo']}" # no problem```
young sand
glacial harness
#

Thank you :D

flat krakenBOT
#

Signed-off-by: RedGuy12

Description

Resolves #3923

I moved the --include documentation down below all the --exclude options since exclusions are are calculated before inclusions, so this reads better.

Checklist - did you ...

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

Describe the style change

I've inherited some code with odd import conventions. It would be nice if black forcibly moved the imports into lumps together.

Examples in the current Black style

import os

if a:
  import system
  print('here')
  import os.path

import platform

Desired style

import os
import platform

if a:
  import os.path
  import system

  print('here')

Additional context

In theory this...

late dewBOT
#

:incoming_envelope: :ok_hand: applied timeout to @wheat island until <t:1701122145:f> (10 minutes) (reason: burst spam - sent 8 messages).

The <@&831776746206265384> have been alerted for review.

flat krakenBOT
#

$ black .
error: cannot format ..../init.py: INTERNAL ERROR: Black produced invalid code: f-string: expecting '}' (, line 35). Please report a bug on https://github.com/psf/black/issues. This invalid output might be helpful: /tmp/blk_pq9jt9me.log

Oh no! πŸ’₯ πŸ’” πŸ’₯
63 files left unchanged, 1 file failed to reformat.

The line is this:

f'SQL string to apply to input CSV (i.e. "select * from stdin"), or apply a built-in aggregation: {', '.join([f"\"{r}\"" for r in existing_repo...
flat krakenBOT
#

Describe the style change

When a long expression includes parenthetical expressions or functions, it would be better to put parentheses around the whole expression and wrap before operators, rather than wrapping inside an arbitrary set of existing parentheses.

Examples in the current Black style

if this_very_long_variable_name != float(
    "inf"
) and other_very_long_variable_name == float("inf"):
    pass

test = this_very_long_variable_name * floa...
#

Description

The descriptions for some options were inconsistent between the --help command and the the_basics documentation page. This PR unifies the two, as well as making the order consistant. Finally, the -x option was previously not mentioned at all in the documentation, so I added it.

Checklist - did you ...

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

Describe the bug

When a single-argument function definition breaks across multiple lines, Black will add a trailing comma (after the argument) in some cases but not others.

To Reproduce

For example, given the following Black adds a trailing comma after the annotation on x in the first case, but not the second, third, or fourth:

# Black inserts a trailing comma after the first argument's annotation here.
def long_function_name_goes_here(
    x: Callable[List[...
flat krakenBOT
#

Describe the bug

A Python file containing a string literal assignment longer than the line length limit is not reformatted if the string literal doesn't contain any whitespace characters.

To Reproduce

For example, take this code example.py:

long1 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
long2 = "This is a long line that is longer than 88 characters. I expect Black and Ruff to sho...
half meteor
#

Another finding on the diff-shades preview failures:
I tried to print the memory usage when it's running w/ these changes: https://github.com/ichard26/diff-shades/compare/stable...yilei:diff-shades:sleep

So there appears to be a memory leak but only sometime

#

The failed run's memory usage keeps growing overtime when it formats each file (not strictly though as sometime it decreases just a little bit)

flat krakenBOT
flat krakenBOT
#

Describe the style change

I came across a strange formatting of the function declaration in the presence of generic typing. As a minimal example, I will give a function with one argument:

def func[T](argument: argument_type) -> return_type:
    pass

In this example, type T is not used, but you can also come up with a function in which type T is used, for example, using collections.abc.XXX[T] instead of argument_type and return_type.

It is assumed that th...

flat krakenBOT
#

Description

When transforming fmt:off into standalone comments, a new node is generated for fmt:off, and in this procedure, the initial indentation of fmt:off is not retained. Black code consistently converts fmt:off/on into standalone comments before proceeding with additional formatting. Consequently, the formatting of fmt:off is disrupted, even when it is not within the specified line range.

I addressed this issue by retaining the indentation of fmt:off ...

flat krakenBOT
ionic mica
#

What will happen to black

#

when there's Ruff

dense jungle
#

so far the outcome seems to be that we got more friends reporting useful feedback

plain atlas
#

I don't see a reason to stop using black any time soon

#

black is easier for users to contribute to (because the users using a python formatter are more likely to know python than rust)

flat krakenBOT
ionic mica
#

in the JS world

rugged sparrow
flat krakenBOT
flat krakenBOT
#

Description

As discussed in #4062 with @JelleZijlstra

Add new flag for tests, --no-preview-line-length-1, to be used for test cases known to not work in preview mode with line-length=1. Also split out the problematic cases in three cases to separate files. Removed now redundant file which explicitly tested preview annotations with line-length=1

Checklist - did you ...

  • [ ] Add an entry in CHANGES.md if necessary?
  • [ ] Add / update tests if necessary?
  • [ ] Add n...
flat krakenBOT
rugged sparrow
#

could i get reviews on my pull requests please? #4072 and #4076 thanks!

flat krakenBOT
dense jungle
dense jungle
slow ibex
#

i am using construct library: ```py
Var = c.Struct(
'name' / WStr,
'type' / c.Enum(
u8,
unknown=0,
int=1,
dword=2,
float=3,
str=4,
array=9,
),
'value' / c.Switch(
c.this.type,
{
'unknown': c.Computed(None),
'int': i32,
'dword': u32,
'float': f64,
'str': WStr,
'array': List(u32),
},
),
)

this gets formatted to this: ```py
Var = c.Struct(
    'name' / WStr,
    'type'
    / c.Enum(
        u8,
        unknown=0,
        int=1,
        dword=2,
        float=3,
        str=4,
        array=9,
    ),
    'value'
    / c.Switch(
        c.this.type,
        {
            'unknown': c.Computed(None),
            'int': i32,
            'dword': u32,
            'float': f64,
            'str': WStr,
            'array': List(u32),
        },
    ),
)

in particular, this: ```py
'value' / c.Switch(
...
),

becomes this: ```py
    'value'
    / c.Switch(
        ...
    ),

that hurts readability
is it intended?

#

i understand that it makes sense to split it into several lines if expression after / is long
in this case it is indeed long, but it is already split into several lines and first line is not that long

slow ibex
#

can i gently ping someone here to get response? πŸ˜„

dense jungle
#

have you tried this in preview style? I think we made some related changes

#

it's sort of an uncommon pattern (an operator with a function call on the RHS), so we probably haven't thought about it too much

#

I don't think it's an unreasonable style though, it follows the operator precedence

slow ibex
dense jungle
slow ibex
#

i dont really know how to describe it

dense jungle
#

something about line breaks in binary operations with a function call on the right

slow ibex
#

psf/black#4092

slow ibex
#

Not sure about the title. Feel free to edit it

dense jungle
#

(was just testing that the hook works)

flat krakenBOT
dense jungle
#

I think I'll do a stable release 23.12.0 and an alpha release 24.1a1 with the proposed 2024 stable style today, cc @elder tusk

plain atlas
#

oooh nice

#

I am lurking in this channel constantly, yes

plain atlas
#

Prettier failed

dense jungle
#

ahead of you πŸ™‚

plain atlas
#

nice

#

github caching moment

#

prettier passed

flat krakenBOT
#

Closes #4042.

Replacing #4064. I need a branch in this repo instead of my fork so I can create an alpha release from it.

This should mostly become the stable style. parenthesize_conditional_expressions and wrap_long_dict_values_in_parens should be reverted unless the issues currently open for them (listed in #4042) are fixed.

flat krakenBOT
dense jungle
#

two releases for the price of one

flat krakenBOT
flat krakenBOT
#

Describe the bug

Minor bug, but it seems that the extra dependencies for the d extra are being installed by default on 23.12.0. This can cause some issues on docker containers and such where gcc isn't installed, as the extra dependencies (aiohttp, and frozenlist) don't seem to have wheels.

To Reproduce

On a non-windows machine (I've done it on Ubuntu, and it also seems to happen on Linux github action runners) Make a new venv, source it, and install black:

...
flat krakenBOT
#

Description

Fix #4107, in a fairly hacky way though.

Hatch will strip out parenthesis in the extras if it thinks it doesn't need them. We can, however, add a meaningless restriction like and python_version >= '1' to force hatch to use our parenthesis. Extremely hacky, and I would understand if we don't want this to be merged until a cleaner hatch fix is upstream. Also happy to come up with another way of essentially just having true in the spec, but I couldn't find one with a qu...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

Black crashes when trying to format code containing a string inside an f-string that uses the same type of quotes. This is valid syntax as of python 3.12.

To Reproduce

For example, take this code:

#! /usr/bin/env python3

print(f"{"a"}")

And run it with these arguments:

$ black --verbose --target-version py312 source.py

The resulting error is:

Identified `/` as project root containing a file system...
flat krakenBOT
flat krakenBOT
#

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

I came across the below code snippet today. black==23.12.0 does not remove the extra space after the f-string's colon:

some_float = 5.0
some_string = f"{some_float: 0.3f}"

I am using Python 3.11.7.

Describe the solution you'd like

I would like black to remove the extra space after the colon, autoformatting to:

some_float = 5.0
some_string = f"{some_float:0.3f}"

**D...

flat krakenBOT
#

Describe the bug

This is regarding the blank_line_after_nested_stub_class preview style. If the class body ends with a function definition with ellipsis, it fails to recognize to add the blank line.

To Reproduce

For example, take this code and add it to a file.pyi stub file:

class TopLevel:
    class Nested1:
        foo: int
        def bar(self): ...
    field = 1

    class Nested2:
        def bar(self): ...
        foo: int
    field = 1

...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

The preview style description says that the blank line won't be added if the body contains only ..., but it seems that Black is adding an empty line nevertheless.

To Reproduce

For example, take this code:

class Top:
    class Nested1: ...
    class Nested2:
        pass

And run it with these arguments:

$ black file.py

The resulting code is:

class Top:
    class Nested1: ...

    class Nested2:
   ...
flat krakenBOT
late dewBOT
#

:incoming_envelope: :ok_hand: applied timeout to @elder bay until <t:1703057903:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

valid halo
#

Hello, the --preview feature seems to not working for multi line """ strings. as a result the indentation gets messed up if there is a large piece of text (prompts) in the code. Is there anything I can do about it?

neon loom
#

Got a pastebin or a small repo with black playground to share?

flat krakenBOT
#

Describe the style change

I am working on Ruff's formatter and implementing Black's preview styles. We reviewed the allow_empty_first_line_before_new_block_or_comment preview style and decided not to implement it because it leads to inconsistent formatting after moving or deleting code or requires more manual intervention.

Examples when allow_empty_first_line_before_new_block_or_comment is enabled

I work on a refactoring and start with the following code:

de...
flat krakenBOT
#

Describe the bug

Our build pipeline is executing the following command to generate a requirements.txt that will be used to create a virtual environment to execute to the build afterwards:

poetry export --with dev --with-credentials -o requirements.txt

Since our project has black as a development dependency, the file will also contain the dependencies required by black. However since we upgraded to blackversion 23.12.0, when the pipele installs the dependencies u...

flat krakenBOT
#

This is not a proposal for a specific style change but feedback related to the parenthesize_long_type_hints, wrap_long_dict_values_in_parens and parenthesize_conditional_expressions preview styles.

I started implementing the said preview styles in Ruff. Implementing these styles proved challenging, making me take one step back and evaluate the proposed design changes. I concluded that the preview styles improve the overall formatting but don’t fix the underlying problem. I believe t...

silent knoll
flat krakenBOT
neon loom
#

Is there a quicker way than PR'ing this commit? I see I can no longer pushing directly to main

flat krakenBOT
#

This is a purely informative question, any issue I had with this I already managed to solve by other means.

The starting point is this: Windows 11 (in a semi-bloated environment), not a great laptop (8GB RAM and i7, but still) and everything running on an SSD (NVMe, PCIe 2x4, IIRC). And the huge file I attempted to pass to black:

Before formatting

  1 676 172 Lines
242 696 884 Characters
        219 MB


After formatting

  4 802 985 Lines
290 934 893 Characters
     ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Hey ,
i am using black as a pre-commit over a container and i am trying to install and update this plugin to use it over a application.

**this is my config

I am getting an error asking for some stage. i tried adding a stage parameter also but it is not picking it. any suggesting that you can give...

warm crow
flat krakenBOT
#

Fixes #4065, closes #4067, closes #4041

See comment in https://github.com/psf/black/pull/4041#issuecomment-1871863867

The two possible fixes are both not ideal. Changing the names of the stages guarantees that things will break with new pre-commit later this year. Raising the minimum pre-commit version doesn't make things work for users who currently have issues, it just results in a better error message. Meanwhile, users who want Black to run in specific stages in pre-commit can just s...

flat krakenBOT
#

Verified with https://black.vercel.app/?version=main

Describe the bug

Black fails to parse format strings (f-strings) where an express

To Reproduce

Default black settings with this source code

f"{""}"

The resulting error is:

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

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

Black formats multi-line strings in keyword arguments of methods ignoring the continuation visual indent.

To Reproduce

For example, take this code:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "lorem",
    help="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt"
         " ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation"...
flat krakenBOT
#

Describe the bug

Apologies if this is a duplicate; I have read:

Based on https://github.com/psf/black/pull/3959, Black should support e.g. this: # pylint: disable=redefined-outer-name # fmt: skip and yet I cannot get it to work on the newest Black version.

I have the following line:

client = billingdataservice.app.test_client() # pyli...
flat krakenBOT
#

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

I'd quite like to have an option to have single-quoted strings be the default.

Problem as described by the Blue formatter ( https://blue.readthedocs.io/en/latest/ ):
"blue defaults to single-quoted strings. This is probably the most painful black choice to our eyes, and the thing that inspired blue. We strongly prefer using single quoted strings over double quoted strings for everything except docstrings and triple quot...

flat krakenBOT
#

Description

Black has regex options to exclude/include files from processing: exclude, extend-exclude, force-exclude, include.

As other options pyproject.toml can be used to set values.

For example:

extend-exclude = '^file_one\.py|file_two\.py$'

However that's not too readable especially if the list was longer...

Thankfully black accepts regexs with newlines:

extend-exclude = '''
^
file_one\.py
|file_two\.py
$
'''

This wor...

elder tusk
#

what's next for 2024 style? should we make a2?
i think overall things are shaping up nicely.
we should leave out string_processing and hug_parens_with_braces_and_square_brackets. we should also probably leave out wrap_long_dict_values_in_parens (it has three open issues, including crash)

dense jungle
#

i'll look more next week

flat krakenBOT
#

Description

Resolves #4143. I attempted to fix https://github.com/psf/black/pull/2970#pullrequestreview-932691073 while I was at it. However, that's a larger undertaking since _contains_fmt_skip_comment() requires a mode parameter and make_comment() doesn't - I'd have to add it to every caller of make_comment() and each of its callers, etc. Let me know if it's desired anyway.

Checklist - did you ...

  • [y] Add an entry in CHANGES.md if necessary?
  • [y] Add / update tes...
wispy creek
#

Hi! Why the last enum case is not formated by Black?

class ResultType(IntEnum):
    OK = (0,),
    NOT_FOUND = (1,),
    ANOTHER_ERROR = 2
glacial drum
wispy creek
glacial drum
#

2 and (2,) are not the same, so that would change the meaning

#

the first is an int, the second is a tuple with an int in it

#

I am guessing you actually mean the code to be this, right? ```py
class ResultType(IntEnum):
OK = 0
NOT_FOUND = 1
ANOTHER_ERROR = 2

wispy creek
young sand
#

It sounds like maybe you thought you had this code:

class ResultType(IntEnum) :
    OK = 0
    NOT_FOUND = 1
    ANOTHER_ERROR = 2

But actually you had this, which means something different (the trailing comma creates a single-element tuple when it occurs on the right-hand side of an assignment) :

class ResultType(IntEnum) :
    OK = 0,
    NOT_FOUND = 1,
    ANOTHER_ERROR = 2
wispy creek
#

hmm it's possible, thanks!!

flat krakenBOT
#

I'm building a developer tool that generates code. The code we want to generate should be formatted according to black. The only way I've found to do that until now has been to write the new file to disk and then call black executable to format the file. But this seems pretty unnecessary and wasteful in time and performance.

It could be much better if I could just call black through some python library/API function and provide it a string variable with the unformatted python code. I wou...

flat krakenBOT
#

Using Black Formatter extension on vs code which uses v23.10.1

for some reason I get no line formatting by default (of 79 characters) however things work when I declare line-length and any value (including the default of 79)

image

I feel like this should be an easy bug to fix (by default just declare it with 79) not. But hopefully it will help those that got stuck with this issue https://github.com/...

flat krakenBOT
flat krakenBOT
#

Describe the bug

Can not format method code when method str parameter length default value too long

To Reproduce
env: python 3.8.10
black: 23.12.1

def demo_method(
    param1="this is a long long long long long long long long long long long long long long long long long long long long string",
):
    a = (
        "this is a long long long long long long long long long long long long long long long long"
        " long long long long string"
    )
    ...
flat krakenBOT
#

Describe the bug

Internal crash

To Reproduce

Run the code down below

For example, take this code:

  File "src/black/__init__.py", line 1476, in assert_equivalent
  File "src/black/parsing.py", line 140, in parse_ast
email = "test@example.com"
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
    filter=f"mail eq '{email}' or startswith(userPrincipalName, '{email.split("
    @ ")[0]}')",
    count=True,  # required
)

And ...

flat krakenBOT
flat krakenBOT
azure plank
#

Messing around with preview, when formatting this py for _ in []: for _ in []: for _ in []: ValueError(f"first part {'long long long long long long long long long long contents'}")
it becomes this playground link py for _ in []: for _ in []: for _ in []: ValueError( "first part" f" {'long long long long long long long long long long contents'}" )
Why is this? I would expect it to be formatted like this py "first part " f"{'long long long long long long long long long long contents'}"
instead.

elder tusk
#

my guess would be it's because it's a pretty common bug for people to forget the trailing space when using implicit string concatenation. having the space be leading makes it obvious. i think this is the issue where this was decided, if you want to read through the history: https://github.com/psf/black/issues/182#issuecomment-552132608

#

(but i agree it's not an open and shut case, when manually doing implicit string concatenation i do it the other way. if you split things differently, black won't resplit unless you're over line length)

#

(also note that this feature will not make it into the 2024 stable style)

flat krakenBOT
#

Description

According to the issue #4149, the ternary operation expression was not correctly being formatted. This was caused by the existing black's logic to determine whether the base of the exponential expression is simple or not, meaning whether it does not have parenthesis or brackets and such and just accepting naming or dotted lookups. Essentially, the existing logic was to loop over the direction (base backwards, exponential forward) and find whether a bracket or pare...

flat krakenBOT
flat krakenBOT
#

Describe the bug

Trying to use Black in github actions and it is failing after reformatting.
Shouldn't it be passing after reformatting without errors ?

name: Lint

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: psf/black@stable

To Reproduce
use black in github action

The resulting error is:
failing github action after reformatting

would reformat /home/runner...
clever peak
#

encountering a bug.

import asyncio
from telebot import asyncio_filters
from telebot.async_telebot import AsyncTeleBot
from telebot.asyncio_handler_backends import State, StatesGroup
from telebot.asyncio_storage import StateMemoryStorage
from telebot.types import KeyboardButton, Message, ReplyKeyboardMarkup
import logging


state_storage = StateMemoryStorage()
bot = AsyncTeleBot("", state_storage=state_storage)
logger = logging.getLogger(__name__)


def contains(text: str):
    def wrapper(message: Message) -> bool:
        return text in message.text

    return wrapper


class Database:
    def get_balance(message: Message) -> int:
        return 3

    def user_exists_or_create(message: Message):
        return 3


@bot.message_handler(func=contains("Balance"))
async def balance(message: Message):
    await bot.send_message(message.chat.id, "Please wait while we process your request")
    shop_database.user_exists_or_create()
    await bot.send_message(
        message.chat.id, f"Your balance is ${shop_database.get_balance()}", reply_markup=ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("πŸ”™ back")
    ))
    return


if __name__ == "__main__":
    shop_database = Database()
    bot.add_custom_filter(asyncio_filters.StateFilter(bot))
    asyncio.run(bot.polling(non_stop=False), debug=True)```
#

when i format this with black

    await bot.send_message(
        message.chat.id, f"Your balance is ${shop_database.get_balance()}", reply_markup=ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("πŸ”™ back")
    ))``` get's converted to 
```py
    await bot.send_message(message.chat.id, f"Your balance is ${shop_database.get_balance()}", reply_markup=ReplyKeyboardMarkup(resize_keyboard=True).add(KeyboardButton("πŸ”™ back"))
#

which is missing an closing ), sorry for the noise, this was what i was able to distill it to so that i could repro reliable, let me know if something like this has been reported before

misty trench
#

hi all! New around, sorry if my questions is obvious. Is there an approximate schedule for stable 2024?

flat krakenBOT
#

Description

On the documentation page "Using Black with other tools" the .flake8 example included E7041 in the ignore, but none of the other examples include this ignore and there is no mention of this above this. Removing E7041 from the example.

Checklist - did you ...

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

which thinking about it means i should be opening an issue on MS black extension repo maybe

lunar mulch
#

This is probably a better channel to ask in! Is there an ETA for when Black v24.0.0 will be released? I am in the middle of a repository cleanup and would LOVE to include the new preview style, but I need it to be stable before I merge πŸ˜…

#

Ah, I see above end of the month. Great work, and I am looking forward to it!

flat krakenBOT
#

Given this input:

x = {
    "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": (
        "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx"
    ),
}

The current draft new stable style outputs:

x = {
    "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx",
}

This is because the string is long enough that it doesn't fit within the line length even i...

azure plank
#

How did I miss dummy_implementations, I 100% agree with hauntsaninja that it's a massive qol improvement

flat krakenBOT
rare kernel
#

Black formatter format like this
Any way to remove the remove the red squiggly line?

bright glacier
#

Black doesn't really format like that, do you have line wrapping enabled in VSC?

rare kernel
#

I havent touched any of the settings here

bright glacier
#

well, black doesn't format like that so I doubt it's black's fault

#

what's the error indicated the squiggly line anyway?

rare kernel
bright glacier
#

Right. Black can't fix that.

rare kernel
#

Can I disable that type of formatting

bright glacier
#

Black is not causing that.

#

Black won't even be able to format your code as that's invalid syntax (and will fail to parse).

bright glacier
rare kernel
#

Thats the formatted code
If I put it into one line like this
st.set_page_config(page_title="Results", page_icon=":chart_with_upwards_trend:", initial_sidebar_state="collapsed")

black changes it into

st.set_page_config(
    page_title="Results", page_icon="πŸ“ˆ", initial_sidebar_state="collapsed
")
rare kernel
#

Why isnt it happenong here

bright glacier
#

I dunno.

#

Does it occur if you run black on the file via the terminal?

rare kernel
#

nvm this

st.set_page_config(
    page_title="Results", page_icon="πŸ“ˆ", initial_sidebar_state="collapsed"
)
rare kernel
#

in vscode

bright glacier
#

well yeah, but we're trying to figure out why black.now.sh isn't reproducing it

#

removing vscode as a variable is part of that process

rare kernel
#

how do i format without vscode

bright glacier
#

pip install black and run python with -m black <path-to-your-file>

#

actual commands will vary on how you use pip and python on your system

rare kernel
#
st.set_page_config(
    page_title="Results", page_icon="πŸ“ˆ", initial_sidebar_state="collapsed"
)

Format like this

IDK why vscode black put the " in a new line

#

It also dont go over the 80ch col limit

#

wiht the "

bright glacier
#

Are you using a different version of Black under VSCode? That's the last variable on black's end that could cause this (well other than any black configuration that may be present).

#

I'm still not convinced this is black's fault, although it seems strange for vscode as well.

rare kernel
#

maybe a bug in the vscode black extention?

bright glacier
#

maybe, but it's a pretty strange bug

rare kernel
#

This is the version I have in pip

#

Anyways vscode black is happy with the way pip black formatted it

#

for now ill use that

bright glacier
#

I'm sorry that you're dealing with this, but I'm at a loss on how this could happen. I would take a closer look if I had time, but I don't.

#

Perhaps you could reach out to the VSCode Python folks and see if they have any ideas?

rare kernel
#

nah its all good, not big deal
I'll create a issue in there github repo later

#

their*

flat krakenBOT
flat krakenBOT
#

Describe the bug

I'm on MacOS. I try to run Black through Docker, but the container promptly stops with an ImportError related to the missing aiohttp dep.

To Reproduce

docker run -d -p 45484:45484 --pull always pyfound/black blackd --bind-host 0.0.0.0
# returns c42cfd39d8047d840beb779ea529005ef4d5682b060bcbca9b154e940bd346ab
docker logs -f c42cfd39d8047d840beb779ea529005ef4d5682b060bcbca9b154e940bd346ab
Traceback (most recent call last):
  File "/op...
orchid crow
#

I know it is not maintained by Black's dev

flat krakenBOT
flat krakenBOT
dense jungle
flat krakenBOT
unborn heart
dense jungle
#

sometimes if I retry enough times it works

#

I haven't had a chance to investigate deeper

#

seems related to memory usage or something

#

i guess for your PR it's pretty clear it won't affect formatting anyway

unborn heart
#

Got it, thank you.

dense jungle
#

also just commented on the issue

flat krakenBOT
flat krakenBOT
#

Describe the bug

Black unexpectedly can't parse complex conditional list comprehensions inside of f-strings. Check out the example below.

To Reproduce

For example, take this code:

subdir_options = f" ({", ".join([dir for dir in subdirs if dir != "tests"])})" if subdirs else ""

And run it with these arguments:

$ black file.py --target-version py312

The resulting error is:

Cannot parse: 128:71: subdir_options = f" ({", ".jo...

azure plank
#

πŸŽ‰

wintry grove
#

is it OK to ask about the ruff formatter here?

silent apex
dense jungle
wintry grove
#

ok thank you, appreciate the response and the direction

elder tusk
#

ruff formatter bases its style choices on black, so this is a reasonable place to discuss that. but e.g. if you want help getting started using ruff formatter or something, ruff discord is the way to go!

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
dense jungle
#

time for 24.1

flat krakenBOT
flat krakenBOT
bright glacier
#

congrats!

dense jungle
#

the wheels aren't built yet πŸ˜›

bright glacier
#

are you blaming me for not making mypyc fast enough πŸ‘€

dense jungle
#

it looks like the actions are queued, so I think I should blame GitHub for not giving us enough compute resources

#

(but of course I'm grateful they give us CI infrastructure for free)

bright glacier
#

imagine the productivity increase if we didn't have to wait for CI, would be truly revolutionary

#

but yes, GHA is great as-is, I'm just poking fun :P

flat krakenBOT
dense jungle
elder tusk
#

hooray!

flat krakenBOT
#

Describe the bug

Running black 24.1.0 (without --check) can produce filenames in user's cache folder that are too long for some filesystems e.g. eCryptFS only allows filenames that are 143 chars long

The resulting error is:

Traceback (most recent call last):
  File "/home/hottwaj/.pyenv/versions/3.10.2/envs/test-venv/bin/black", line 8, in 
    sys.exit(patched_main())
  File "src/black/__init__.py", line 1593, in patched_main
  File "/home/hottwaj/.pyenv/versions/3.10.2...
flat krakenBOT
flat krakenBOT
#

Describe the bug
Changes introduced to cache key calculations by #4096 made Black unusable with cache dir located on eCryptfs container which limits the maximum file names to 143 characters. eCryptfs is usually used to protect user home directories, where the default .cache/black location is created.

#4096 added another sha256 hexdigest to the cache file names which now overflow the 143 characters limit.

To Reproduce
Set up and mount eCryptf...

flat krakenBOT
flat krakenBOT
#
  • Ensure total file length stays under 96
  • Hash the path only if it's too long
  • Proceed normally (with a warning) if the cache can't be read

Fixes #4172

Description

Checklist - did you ...

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

welp seems like this new cache filename doesn't work on windows, I guess I can't use | in a path?

#

ok @ worked

#

fun fact: if you set your max line length to an 80-digit number, Black must always have been broken on eCryptfs. I wonder why nobody reported that

flat krakenBOT
flat krakenBOT
drowsy jolt
# dense jungle fun fact: if you set your max line length to an 80-digit number, Black must alwa...

some PyPI stats from henryiii in the [PyPA server](#1128441623974531072 message), here's the most popular tool.black.line-length values:


All the ones over 100:

120: 5755
88: 3578
79: 2876
100: 2714
80: 834
99: 811
119: 485
110: 359
90: 269
95: 169
140: 165
160: 112

(Less than that, then I probably should start including strings & the other way(s?) to specify it like line_length) Total is 19,076 pyproject.tomls that have tool.black

dense jungle
flat krakenBOT
#

@henryiii shared some useful data on common Black configurations in pyproject.toml files found on PyPI. A few pieces of weirdness stood out:

  • Some people set line-length to a string, e.g. line-length = "100". This is very rare, about 25 instances total out of almost 20k (~0.1%).
  • We allow both line_length and line-length. In Henry's sample, line_length was used about 3% as much as line-length. Our documentation only uses the hyphenated versions.

This might cause problems wh...

flat krakenBOT
#

Describe the bug

After upgrading to 24.1.0 I got a series of reformatting messages like the following:

@@ -1,6 +1,7 @@
 """My file"""
+
 from datetime import datetime, timezone, date
 from dateutil.tz import tzutc  
 
would reformat /__w/7/s/.../myfile.py

Oh no! πŸ’₯ πŸ’” πŸ’₯
93 files would be reformatted, 28 files would be left unchanged.

To Reproduce

For example, take this code:

 """My file"""
 from datetime import datetime, timezone, date
 fr...
flat krakenBOT
#
lunar mulch
#

Excellent! I just converted over a moderately complex project with positive results. I was, however, a bit surprised that the vast majority of changes were blank line additions and deletions 🀣 (upgrading from v22)
Overall, I like the formatting changes quite a bit, nice work!

#

(also... 120 line-length gets my vote every time! πŸ€“)

flat krakenBOT
#

Description

This adds a script (Python 3.10+ required) to produce a JSONSchema. I've added
it to the package, and provided a helper function / entrypoint to allow
validate-pyproject to use it. You can try it out like this:

$ virtualenv .venv
$ py -m pip install -e . validate-pyproject[all]
$ validate-pyproject -v pyproject.toml
[INFO] black.schema.get_schema defines `tool.black` schema
[INFO] validate_pyproject.api.load_builtin_plugin defines `tool.distutils` schema
[INFO...
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

 This resolves the issue mentioned in issue #4180, where a newline will
 be added to a docstring comment (that is approaching the line limit),
 even if the docstring contains a newline before the closing quotes.

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
#

In #4096 I added a list of current preview/unstable features to the docs. I think
this is important for publicizing what's in our preview style. This PR adds an
automated test to ensure the list stays up to date in the future.

This doesn't work with pre-commit (which is why I'm making this a draft). Haven't been able to figure out a way to fix that. I considered making it a unit test instead, but that will probably get redistributors unhappy.

flat krakenBOT
#

When running black on the following code:

text = re.sub(
    "([_a-zA-Z0-9-+]+)(\.[_a-zA-Z0-9-+]+)*"
    "@([a-zA-Z0-9-]+)(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})",
    '\g',
    text,
)
text = re.sub(
    "(ftp|http|https):\/\/(\w+:{0,1}\w*@)?"
    "(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?",
    '\g',
    text,
)

I get the following warnings (written twice):

:2: SyntaxWarning: invalid escape sequence '\.'
:3: SyntaxWarning: invalid escape sequence '\.'
:...
flat krakenBOT
placid oasis
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug
In 2023 we used experimental-string-processing. This was enabled without preview style enabled.
However now in 2024 the experimental string processing flag was removed and replaced with
enable-unstable-feature = ['string_processing']

However this feature requires turning on the preview feature.
And now the files are additionally formated based on the preview style.

To Reproduce

preview = true
enable-unstable-feature = ['string_processing']
skip...
#

Describe the bug

Additional brackets wrap the expression if the line reaches 182 chars in length. Is it expected behavior?

To Reproduce

For example, take this code:

test = [
    TestClassNameForDemo(prop1=key, prop2=value, prop3=value, prop4=value, prop5=value, prop6=value) if "option" in test_dict.keys() else TestClass(name=key, default_value11=value)
    for key, value in test_dict.items()
]

And run black for it (24.1.0 or newer). As a result...

azure plank
#

I was reading through the black issues, and I wonder if it would be worth adding a C: unstable style issue label since things like string_processing have been moved to unstable, or if it would be too much work swapping between preview and unstable tags as features get moved.

dense jungle
azure plank
# dense jungle Good point, I do think it might be annoying to maintain as we move features betw...

Sounds reasonable to me. While from what I've seen it's not common, it's also not unprecedented to have the broken feature name in the title. I suppose the only other consideration would be on issues where the cause isn't initially known. From the perspective of a reader, shuffling tags on issues seems like a less substantial action than editing the title, but I'm not sure what other people's take on that would be/what the general culture around it is. I'm also not familiar enough with github from a maintainer's perspective to know if there are different perms for adding tags vs editing issue titles that might need to be changed.

dense jungle
dense jungle
#

Also you're right that it might not be clear initially which preview feature is responsible, but we can always change the title later

azure plank
#

Looks good. My one complaint would be I vastly prefer the look of the feature name being in a code block, but it's mostly just a nitpick.

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

@JelleZijlstra I've made the requested changes. My thought process:

  • I updated the compatible_configs folder (and added some for pycodestyle). This was an oversight in #3888. Not sure how useful this folder is, but I didn't think removing it would be in scope here.
  • It turns out that E704 is already disabled by default, so #3888 actually didn't document it correctly. Fixed that here.
  • I moved the pycodestyle section above Flake8 and moved the reasoning section there as well. Since F...
flat krakenBOT
#

Describe the bug

Black cannot parse fstrings with one line if statements

To Reproduce

For example, take this code:

a = f'{'1' if 1 else '2'}'

And run it with these arguments:

$ black file.py --target-version py39

The resulting error is:

error: cannot format cogs\black.py: Cannot parse: 4:11: a = f'{'1' if 1 else '2'}'

Oh no! πŸ’₯ πŸ’” πŸ’₯
1 file failed to reformat.

Expected behavior

A "cannot parse" error does not occ...

flat krakenBOT