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
1 messages Β· Page 6 of 1
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
A minimal suggestion in docs
CHANGES.md if necessary?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
At least got us to use hatch: https://github.com/psf/black/pull/3965 - Will take any pointers on how to make it compile the wheel ...
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
I don't think is the right channel to ask for help on this friend.
Thanks!
Yes, this should be preview style only.
Sorry was in meetings and missed you merged. Thanks π
Do we want to get a hotfix out today for the github action failure?
yeah probably. We've accumulated a few other improvements too
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.
sounds good, yes the docs page should be good. I always follow it when making a release
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?
just merged one. there's a couple other PRs that are near ready but they can wait
We need https://github.com/psf/black/pull/3957 for GitHub action - So I'mma gonna merge that
Description
Fixes #3953
Checklist - did you ...
Add an entry in CHANGES.md if necessary?
Add / update tests if necessary?
Add new / update outdated documentation?
I guess we should open an issue for Windows Doc builds failing
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 π
sure that's fine too, just means one more thing to do later
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 π
sure, it's really annoying to edit them manually
I might write in python so it works for our lovely Windows people π
for extra points, make it also clean up the changelog π
Yeah, I'll do that too. python I can write unittests too cause I don't trust myself
https://github.com/psf/black/issues/3970 - Add any features I forgot. No wife this week so I might actually write it tonight π
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
We not compile black in docker. It takes a long time, especially since we do it twice (for aarch64 + x86_64).
Let's see if we can make those steps happen in parallel
(Any GitHub action help here would be appreciated)
^^ 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 π¦
but the resulting image is several times faster π
Ok - all built - Cutting release
Our docs should auto build etc. right?
Seems CI will move the stable branch and then a docs build will kick off?
yes, all should be automated
thanks for doing the release!
No worries, good to do it after a long break π
Hmm, seems the release breaks black-pre-commit-mirror
It needs some cronjob?
Is your feature request related to a problem? Please describe. Looks like https://github.com/psf/black-pre-commit-mirror/blob/91867dbada8a528dcc51a369d95a9d11a81a26a8/.github/workflows/mirror.yml#L...
Wonder if we can click run now or something and then think of a better way
I just pushed some button there
Yeah seemed to work
Does psf org have access to larger runners? cc: @solid adder ... Would like to move the docker ci there if we can ...
No idea if we have larger runners. I'll ask Ee
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
ef1048d Add Unreleased template to CHANGES.md (#3973) - cooperlees
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
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 ...
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 ...
out of curiosity, do yall use mypy's stubgen at all?
not in Black
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()
Ok. Finally with a non shallow checkout my tests work β¦
Some nice passer-byer informed me! Makes sense. I didnβt realize that limited tags.
Thanks for catching this and opening a PR! I think we should use root_relative_path on L396 , so we apply include logic before symlink resolution
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.
CHANGES.md if necessary?parantheses -> parentheses
CHANGES.md if necessary?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...
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...
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
To Reproduce
Install black[d] in python 3.12
Expected behavior
We install and CI passes
Environment
aiohttp doesn't yet support 3.12
Thanks. Make me sad we could not be ready before GitHub flicked the switch and we create this tech debt, but such is life.
This pull request fixes typos in change log and docs. Following are the fixed typos:
I kindly request the repository maintainers to review and merge it. Thanks!
CHANGES.md if necessary?de701fe Fix CI by running on Python 3.11 (#3984) - hauntsaninja
7bfa35c docs: fix typos in change log and documentation... - shresthasurav
Black https://github.com/psf/black/commit/f7174b
--line-length=88
--safe
def name_4[**name_0](): # type: ignore
pass
...
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.
CHANGES.md if necessary?Fixed a grammatical mistake
single line => single-line
CHANGES.md if necessary?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...
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?
Fix small typo
CHANGES.md if necessary?Maybe
But that change is kinda specific
Like you'd have to be actually interested in reading that doc
I guess good that people are reading the docs, in that case π
I guess this is technically incorrect english, but I wonder if it was done on purpose :|
As noted by @Avasam here, hugging parens with brackets on multiline dictionaries and lists as sole function parameters didn't take into account list unpacking. This PR fixes that shortcoming.
CHANGES.md if necessary?Thanks! A few comments
Thanks! I haven't reviewed this in detail, but it looks promising. Two points:
% 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.
yeah, I think setting to false will fix, but hadnβt yet gotten a chance to test
Removed Grammatical errors
CHANGES.md if necessary?https://hacktoberfest.com/participation/#spam
just putting this out here
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, ...
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.
CHANGES.md if necessary?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(
...
Fixes #4002
I think this only fixes crashes so it doesn't need to go through the preview style,
but not 100% sure.
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.
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)```
yes, I think this would be useful. Thanks!
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 ...
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...
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...
Fixes this.
CHANGES.md if necessary?CHANGES.md if necessary?This PR makes rhs processing prefer more equal signs before breaking the line. Reported here.
CHANGES.md if necessary?Damn, black is active at the moment
I don't think the regex is right, need to care about things like {foo("asdf")=} as well. Also maybe worth using iter_fexpr_spans?
Describe the style change
#3964 handled the most common case from #1811, and I'd like the following cases to be handled too:
foo(
(
1,
2,
3,
)
)
foo([
[
1,
2,
3,
]
])
Thanks, this looks pretty good!
5758da6 Fix bytes strings being treated as docstrings (... - JelleZijlstra
CHANGES.md if necessary?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.
Looks like that might have been closed accidentally due to the PR description in #black-formatter message
As described here, and in referenced issues thereof, Black crashes when standalone comments are sprinkled inside complex multiline blocks. This PR takes a first step in fixing the most obvious cases and aims to get rid of blatant crashing. There are known issues with more nested expressions not being indented correctly, e.g.
[
(
lambda
# a comment ...
Hello
self bot
"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!
possibly enclose the name in quotes ("C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb"). But I don't use Windows and I've heard shell quoting in Windows is weird
PS C:\Users\sasa\Desktop\Lesson 3> "D:\Program Files (x86)\Anaconda\Scripts\black.exe" "C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
β"C:\Users\sasa\Desktop\Lesson_4\Lesson 4
.ipynb"βγ
+ CategoryInfo : ParserError: (:) [], ParentContainsErro
rRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I already tried. But it didn't work.
maybe single quotes instead? for what it's worth that error doesn't come from Black
PS C:\Users\sasa\Desktop\Lesson 3> "D:\Program Files (x86)\Anaconda\Scripts\black.exe" 'C:\Users\sasa\Desktop\Lesson_4\Lesson 4.ipynb'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
β'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
.......well i fixed it https://github.com/psf/black/pull/4017
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
Fixes #4018
Python does not consider f-strings to be docstrings, so we probably shouldn't be formatting them as such. This is the easiest way to fix the issue with the AST check.
Despite its name, I think docstring_preview.py might be testing stable style, which this unfortunately does change
Thanks, definitely an interesting solution.
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?
which version are you using? it looks like we added --color in 2020 (commit 8d6d92aa5b5248b5ff70ebf7977f8af5cbcb10b9)
I think it's because of gitlab or something related.
Removed --color and it works
This image: registry.gitlab.com/mafda/python-linting
Do you recommend another image for this?
No idea, never heard of that and I don't know how Gitlab CI works
seems like it hardcodes black==19.10b0
which just had its fourth birthday
that suggests it's not a well-maintained project
i understand. Thanks
This adds a command-line option --line-ranges=, to tell Black to only format these specified lines.
Fixes #830
CHANGES.md if necessary?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...
When trying to understand the code logic, and looking at coverage reports, branch coverage is very helpful.
CHANGES.md if necessary?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) ...
Seems like you're correct, and diff-shades also found nothing changed by this refactor.
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_...
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...
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...
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!")
+
+...
Fixes #4027.
CHANGES.md if necessary?Black explodes the list in the following:
def foo():
assert long_long_long_long_var == [
0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18
]
If you rename the variable to something short, Black no longer explodes the list.
I wouldn't mind a test involving :=
ecbd9e8 Fix crash with f-string docstrings (#4019) - hauntsaninja
we should do a release in the next few days after the current crop of PRs is merged
Thanks! This looks good, just a few pieces of minor feedback.
This has been a long-standing feature request, so it's great to finally see it in Black.
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...
66008fd [563] Fix standalone comments inside complex bl... - henriholopainen
2e4fac9 Apply force exclude logic before symlink resolu... - hauntsaninja
Hello! :)
I noticed a typo in the docs.
The flake8-bugbear error code was mistyped as "E950" instead of "B950".
CHANGES.md if necessary?(I suppose none of the above applies...)
The diff-shades preview checker seems to be failing on the CI?
yes, that's been happening intermittently. I haven't been able to find useful logs to debug it
Is this related to a problem? Please describe.
Issue #3124 / PR #3129 added support for parsing --target-version from [project.requires-python] in pyproject.toml. But I canβt find any mention of this in the docs for --target-version or elsewhere.
Describe the solution you'd like
A paragraph describing the support and limitations, with an example.
**Describe alternativ...
1a7d9c2 Preserve visible quote types for f-string debug... - henriholopainen
72e7a2e Remove redundant condition from `has_magic_trai... - bluetech
the docker build on main has been running for 47 minutes... π±
should https://github.com/psf/black/pull/3940 be applied to black-pre-commit-mirror?
quite possibly, feel free to send a PR
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...
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.
What's possible is 1) get rid of the two-pass format in Black; 2) skip assert_stable when --line-ranges is used (https://github.com/psf/black/blob/58f31a70efe6509ce8213afac998bc5d5bb7e34d/src/black/__init__.py#L1472)
src/black/__init__.py line 1472
lines = adjusted_lines(lines, src, dst)```
I think it's an improvement! Splitting the one in the middle is not usually a choice a human would make.
Moreover, the change here isn't super common or controversial, so I think churn costs aren't too high.
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...
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)
-...
We close ...
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...
Small refactor + fix. Fixes #4036
CHANGES.md if necessary?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?
yes, that might be it. If so, we can consider running it on fewer projects
I wonder if there is a good way to cap it at like 80% of the CPU, it will take longer time it might not get killed this way.
maybe we have a perf regression?
Possible, but https://github.com/psf/black/actions/runs/6807549150/job/18510596967 is a successful run last night based on current main with pending changes, Analyze target revision took 10m 54s
I checked a few runs from past week on the main branch they took 10 to 14 minutes.
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...
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.
CHANGES.md if necessary?Is it expected that the playground can't match statements? https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AGdAHldAD2IimZxl1N_WmBasjhgIpJRm9DfswfTHVK7-U27RtCcvConAPxeBZhIzFLWwR4J5lDZ9f93h4U-y9h1zPSvJP4tcEhTz0ZrRS8f59LHYgd3OOKRaNIkYFVCbwTZMZCSkozoe599gj1SFizhchKv3zLAu4JnTpkRhoAAAAAAjaC-ekbT5nYAAZUBngMAAFNSR-yxxGf7AgAAAAAEWVo=
Playground for Black, the uncompromising Python code formatter.
I couldn't find an open issue for that
Try ticking "skip temporary sanity checks" in the settings (bottom left)
yep, but why does that fail on the playground when it works locally?
Because the playground uses a runtime older than 3.10
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...
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
}
}
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 :)
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
black doesn't fix errors
and yes, it does need syntactically valid code or else it will probably fail to format
oh.. so a very dumb question. how come it shows in this video the code auto formatted? https://youtu.be/YapHfCRCpig?t=342
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?
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
badly formatted
It's because Black won't be able to parse the code.
It needs to be able to parse (understand the structure of your code) to be able to format.
ah i understand. is there some other addon that does what i want to achieve
parse and format
yes
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.
i see, thank you for clarifying the difference/expectation
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.
isort occasionally fixes SyntaxErrors for you: https://github.com/python/typeshed/pull/10055/commits/9bf3296654f10069e2b7382ac994d442eb8738e6
But I personally think of that as a bug rather than a feature π
isort also occasionally introduces new SyntaxErrors for you, so, you know β swings and roundabouts https://github.com/PyCQA/flake8-pyi/pull/411/commits/a69c12d4ba436dca486eab8b6c1d6b2d3b04f500
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.
CHANGES.md if necessary?See issue for 2023 here: https://github.com/psf/black/issues/3407
Here's what this issue is:
--previewBackground:
tldr; the 2023 stable style strips newlines after code block opens. This h...
I won't die on a hill, but this makes me sad - One of my most hated things about rust formatting.
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
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)
https://github.com/pypa/bandersnatch/pull/1606/files/979a8a6c8a8da08767fb63a92381ab09394fedc8..52cc530d50ec5c46f2a148ca3d135b26cdb4bb3f - If people want to see the examples ... as I said ... I can live with it. Just not a fan.
updates:
github.com/psf/black: 23.10.1 β 23.11.0
github.com/pre-commit/mirrors-mypy: v1.6.1 β v1.7.0
You still have a choice to use the magic trailing comma case by case here to get the previous behavior
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
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.
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
Additional context
Hi. I'm an engineer at Trunk, which uses and automates Black. This PR is just to add instructions for how to use Black if you are using our free CLI. Please let me know if this isn't appropriate. Thanks!
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...
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):
want to comment on https://github.com/psf/black/issues/4042 ? i don't think it's a foregone conclusion, after all, hug_parens is probably the biggest change we've ever made to black's style
also for folks who dislike hug_parens feature, i'm curious how you feel about multiline_string_handling feature
!pban 1174251412641828878 30d Looks like you're only here to advertise. We're not an ad-board.
:incoming_envelope: :ok_hand: applied ban to @tawny palm until <t:1702630387:f> (1 month).
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
you can use black --skip-string-normalization so it doesn't change quote style. But if your assignments require very specific style, maybe Black isn't the right tool
no just the double quotes are an issue,
but if i have already have the code in double quotes can this command change it back to single quotes?
no
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}'
CHANGES.md if necessary?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).
CHANGES.md if necessary?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...
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.
Version PEP440 specifier soup.
Accepting as this will be temporary until we get a fix into aiohttp 3.9.X.
c4cd200 Make flake8 pass when run with Python 3.12 (#4050) - AlexWaygood
11da02d Handle more huggable immediately nested parens/... - yilei
Let's do it then, I'd like to see if I can get diff-shades to work first though.
80a166f Make black[d] install + test run with 3.12 (#4035) - cooperlees
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...
Fixes #3983
Fixes #3971
Test:
crl-m1:black cooper$ docker build --tag black_3_12 .
...
=> [stage-1 2/2] COPY --from=builder /opt/venv /opt/venv 0.2s
=> exporting to image ...
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.
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 ...
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:
Old flow was ~30-40 mins in total ... so we really won nothing here sadly ...
I'll put up a PR reverting it ...
ec4a152 [docker ci] Revert "parallel" builds in seperat... - cooperlees
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 ...
In the := operator, there's many cases where the:
(point := x, y)
if (attr := sys.modules.get('attr')) and attr.has(type(obj):
if attr := sys.modules.get('attr') and attr.has(type(obj)):
if (attr := sys.modules.get('attr') and attr.has(type(obj))):
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...
89e28ea Permit standalone form feed characters at the m... - tungol
a806298 Disable the stability check with --line-ranges ... - yilei
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:
# flags: --preview from test cases that no longer need itHowever, this should be enough to get useful diff-shades feedback.
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...
CHANGES.md if necessary?: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.
Describe the bug
Given the following code:
@decor(
a = 1,
# fmt: off
b = (2, 3),
# fmt: on
)
def func():
pass
Run black with
$ black --line-ranges=8-8 file.py
Line 8 is pass, and the file will be formatted to:
@decor(
a = 1,
# fmt: off
b = (2, 3),
# fmt: on
)
def func():
pass
Expected behavior
No formatting changes.
Environment
Iff the mypyc issues are all fixed, this should unblock building mypyc-compiled wheels for Python 3.12.
CHANGES.md if necessary?Hopefully this should work following the recent mypy bump π€
CHANGES.md if necessary?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:
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```
Follow https://github.com/psf/black/issues/3746 for updates
https://peps.python.org/pep-0701/, which will be in Python 3.12, adds support for several f-string variations that our current parser won't handle: >>> f"{f"{"f"}&q...
Thank you :D
Signed-off-by: RedGuy12
Resolves #3923
I moved the --include documentation down below all the --exclude options since exclusions are are calculated before inclusions, so this reads better.
CHANGES.md if necessary? (N/A)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...
: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.
$ 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...
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...
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.
CHANGES.md if necessary?Describe the bug
Hello! First of all, thank you for this invaluable tool.
I first ran into this issue on Windows when using black to format code located on a mapped network drive.
This line in get_sources() doesn't ignore symlinks pointing outside of root, which has symlinks resolved by [find_project_root()](https://github.com/psf/black/blob/a0e270d0f246387202e67...
Describe the bug
Related to the new walrus_subscript preview style and has previously been mentioned in this comment
Black removes whitespace around parenthesized walrus operator but preserves it for other binary operations:
x[(a + 4) :]
x[(a := 4):]
I would expect that the walrus operator gets formatted the same as any other binary operator:
CHANGES.md if necessary?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[...
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...
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
A successful run used ~11.5% of ~15.6GB ram in the end >>>> psutil.virtual_memory()=svmem(total=16757780480, available=14827339776, percent=11.5, used=1543008256, free=11242786816, active=1505480704, inactive=3320844288, buffers=217481216, cached=3754504192, shared=24207360, slab=519602176): https://github.com/yilei/black/actions/runs/7067923208/job/19241889065?pr=1
A failed run used up all ram before it was killed: >>>> psutil.virtual_memory()=svmem(total=16757780480, available=24997888, percent=99.9, used=16486572032, free=159674368, active=11400617984, inactive=4878725120, buffers=360448, cached=111173632, shared=9478144, slab=147853312) https://github.com/yilei/black/actions/runs/7068262208/job/19242647307?pr=1
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)
Black 22.12.0 is saying this:
error: cannot format sysaidmin/cli.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_ob7mwr91.log
Log:
The file itself:
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...
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 ...
I noticed typos in the docstrings.
scentific -> scientificgenearting -> generating_convert_unchanged_lines_by_flatterning -> _convert_unchanged_line_by_line (this corrects the function name)CHANGES.md if necessary?so far the outcome seems to be that we got more friends reporting useful feedback
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)
Kind of like Biome and Prettier I'm assuming
in the JS world
could i get someone to look at this?
fixes #4062
CHANGES.md if necessary?Thanks! Could you add a changelog entry?
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
CHANGES.md if necessary?Describe the bug
PEP 701 (Python 3.12) introduced the ability to reuse the same quote type (e.g. ") within f-strings. Black is unable to parse this new structure, causing the formatter to fail.
To Reproduce
For example, take this code:
name = "cool_guy"
works = f"hello {cool_guy.replace('_', ' ')}"
broken = f"hello {cool_guy.replace("_", " ")}" # now possible in Py...
reviewed the first, but now there's a merge conflict in the second
fixed
thanks, will take a look
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
can i gently ping someone here to get response? π
some thoughts in no particular order:
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
just tried, nothing changes
should i open an issue?
if you like. I looked through https://github.com/psf/black/issues?q=is%3Aissue+is%3Aopen+label%3A"F%3A+linebreak"+operator and didn't see any existing issues that look like this
i dont really know how to describe it
something about line breaks in binary operations with a function call on the right
psf/black#4092
Not sure about the title. Feel free to edit it
(was just testing that the hook works)
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
Prettier failed
ahead of you π
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.
two releases for the price of one
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:
...
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...
Thanks for fixing! Now that https://github.com/pypa/hatch/releases/tag/hatchling-v1.20.0 has been released with an upstream fix, maybe a simpler solution might be to just pin to hatchling>=1.20.0 here?
https://github.com/psf/black/blob/35ce37ded7bd8fdd3950af19e7c11f311ee7b8d8/pyproject.toml#L28
Fixes #4078. Next month when the new style is ready for release, we can obviously simplify this a bit.
CHANGES.md if necessary?Thanks for the report and for fixing this twice over!
We'll test the Mac build in CI (looks like the patch still applies, which is main reason for that pin)
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...
Python syntax has changed? Or it hasn't? This line was not flagged in the past.
It would be nice to add a bit more info to that error message (e.g. a link or at least a code what exactly is violated). This way the message is more annoying than helpful.
: ...
field = 1
class Nested2:
def bar(self): ...
foo: int
field = 1
...
previous was unused in is_split_after_delimiter so removed it
rename reversed in enumerate_with_length as reversed is a Python built-in function
Simpify if statements to make them easier to read
Fix docstrings (well-formed and fast-forward is one word, Therefore and Otherwise needs a comma after, remove be be, should be a part instead of apart)
Hello in this pull request, I have added the feature for removing white space after the colon in the f string as outlined in #4112. I want further guidance as to how I can generate the test case for it.
Describe the bug
It seems black does not detect that a files has been changed and needs to be re-checked if the change happens quickly after black has been run in the file.
I'm talking about this feature: [Ignoring unmodified files](https://black.readthedocs.io/en/stable/usage_and_configuration/file_collection_and_discovery.html#ignoring-unmodified-files...
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:
...
Describe the bug
pip thinks that Black 23.12.0 requires aiohttp when the d extra isn't installed
To Reproduce
$ python3.11 -m venv venv
$ venv/bin/pip install black==23.12.0
The resulting installed packages:
$ venv/bin/pip list
Package Version
--------------- -------
aiohttp 3.9.1
aiosignal 1.3.1
attrs 23.1.0
black 23.12.0
click 8.1.7
frozenlist 1.4.1
idna 3.6
multidict...
: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.
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?
Got a pastebin or a small repo with black playground to share?
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...
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...
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...
Hey, could I get https://github.com/psf/black/pull/4109 looked at? Ideally this should probably be merged soon to get in the 2024 stable style
Description
Fixes #4078. Next month when the new style is ready for release, we can obviously simplify this a bit.
Checklist - did you ...
Add an entry in CHANGES.md if necessary?
Add / update...
Upgrade ready for release.
Is there a quicker way than PR'ing this commit? I see I can no longer pushing directly to main
Black fails to format complicated f-string
To Reproduce
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
...
Fixes #4116
This logic was introduced in #3821, I believe as a result of copying logic inside mypy that I think isn't relevant to Black
Removing the int conversion should be fine. See my comment on the issue https://github.com/psf/black/issues/4116#issuecomment-1868845509
Originally reported at https://github.com/psf/black/issues/4042#issuecomment-1852645541
Repro:
class Random:
def func():
random_service.status.active_states.inactive = (
make_new_top_level_state_from_dict(
{
"topLevelBase": {
"secondaryBase": {
"timestamp": 1234,
"latitude": 1,
"longitude": 2,
...
5178614 Fix nits, chain comparisons, unused params, hyp... - Anupya
c80685f Treat walruses like other binary operators in s... - RedGuy12
Fixes #4043, fixes #619
These include nested functions and methods.
I think the nested function case quite clearly improves readability. I think the method case improves consistency, adherence to PEP 8 and resolves a point of contention.
This is a no-op change.
That function was not a good way to tell if something is a function or a class, since it basically only worked for async functions by accident (the parent of a suite / simple_stmt of async function body is a funcdef).
Thanks, but this isn't close to being a correct and functional change. Feel free to reopen the PR once you get things working!
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...
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...
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...
Currently if you make a typo when configuring Black you don't get an error
c359246 [pre-commit.ci] pre-commit autoupdate (#4139) - pre-commit-ci[bot]
Agree, I probably shouldn't have merged the original PR as it wasn't too clear what problem it was solving.
b9ad4da Revert "confine pre-commit to stages (#3940)" (... - hauntsaninja
8e0a9de Remove empty lines before docstrings in async f... - hauntsaninja
2691902 Clean up dead code in magic trailing comma logi... - hauntsaninja
4ceed0b Remove is_function_or_class helper footgun (#4133) - hauntsaninja
Fixes #4113
Authored by dhruvmanila
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"...
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...
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...
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...
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)
i've been procrastinating this a bit but another alpha sounds good, or maybe we can just finalize it
i'll look more next week
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.
CHANGES.md if necessary?Hi! Why the last enum case is not formated by Black?
class ResultType(IntEnum):
OK = (0,),
NOT_FOUND = (1,),
ANOTHER_ERROR = 2
what would you expect it to be formatted as?
All items with the same formatting
class ResultType(IntEnum):
OK = (0,),
NOT_FOUND = (1,),
ANOTHER_ERROR = (2,)
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
At first I had your code, but Black converted it to this:
class ResultType(IntEnum):
OK = (0,),
NOT_FOUND = (1,),
ANOTHER_ERROR = 2
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
hmm it's possible, thanks!!
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...
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)
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/...
m2 = None if not isinstance(dist, Normal) else ΞΌ**2 + Ο**2
m2 = None if ... else ΞΌ**2 + Ο**2
becomes (black-playground)
m2 = None if not isinstance(dist, Norm...
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"
)
...
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 ...
Fixes #2097
I have added the join and split methods so that the split method breaks up the string into a list by separating it with spaces, and then the join method joins the list back into one string with a single space between each word.
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.
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)
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...
Resolves #3758.
CHANGES.md if necessary?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...
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
hi all! New around, sorry if my questions is obvious. Is there an approximate schedule for stable 2024?
by the end of the month!
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.
CHANGES.md if necessary?That doesn't sound like a bug that Black would have. You may be getting confused with some other tool
i'm using the black formatter on VSC
which thinking about it means i should be opening an issue on MS black extension repo maybe
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!
7f60f3d Update using_black_with_other_tools.md to ensur... - kevin-paulson-mindbridge-ai
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...
Reports from @amyreese in https://github.com/psf/black/issues/4042#issuecomment-1890189033:
# before
Thing(
"""
value
"""
)
# after
Thing("""
value
""")
# before
VALUE = [
Thing(
"""
value
"""
)
]
# after
VALUE = [Thing("""
value
""")]
# before
func(
(
value
+ """
something
"""
),
argument,
)
# after
func(
(v...
995e4ad Fix unnecessary nesting when wrapping long dict... - hauntsaninja
How did I miss dummy_implementations, I 100% agree with hauntsaninja that it's a massive qol improvement
Describe the solution you'd like
json schema can let editor which support LSP to complete some configuration file. Such as:
There are many tools have supported json schema:
Can [tool.black](https:...
Black formatter format like this
Any way to remove the remove the red squiggly line?
Black doesn't really format like that, do you have line wrapping enabled in VSC?
I havent touched any of the settings here
well, black doesn't format like that so I doubt it's black's fault
what's the error indicated the squiggly line anyway?
Right. Black can't fix that.
Can I disable that type of formatting
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).
Do you have a sample of code to share that reproduces this issue? Ideally with https://black.now.sh
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
")
In here it format like this
st.set_page_config(
page_title="Results",
page_icon=":chart_with_upwards_trend:",
initial_sidebar_state="collapsed",
)
Why isnt it happenong here
nvm this
st.set_page_config(
page_title="Results", page_icon="π", initial_sidebar_state="collapsed"
)
I have format on save
in vscode
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
how do i format without vscode
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
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 "
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.
maybe, but it's a pretty strange bug
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
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?
nah its all good, not big deal
I'll create a issue in there github repo later
their*
Fixes #4077
Added additional exception handling when calculating the root relative file path.
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...
Somewhat related, does anyone know how to use the pylsp plugin for black? https://github.com/python-lsp/python-lsp-black
python-lsp-server plugin that adds support to black autoformatter, forked from https://github.com/rupert/pyls-black/ - GitHub - python-lsp/python-lsp-black: python-lsp-server plugin that adds suppo...
I know it is not maintained by Black's dev
Resolves #4080
CHANGES.md if necessary?Solution for #4140, raises an exception when toml config file contains a key that doesn't exist in the set of possible cli arguments.
CHANGES.md if necessary?We're getting close to finalizing the stable style! Would appreciate reviews on https://github.com/psf/black/pull/4096 which also adds the new --unstable style and documentation
All looks good to me - I tried to look for typos etc. and couldn't find any.
Going to trust a lot of conversation I didn't part take in.
Assuming the diff shades changes are expected.
Hello, I have submitted a PR (https://github.com/psf/black/actions/runs/7635201817/job/20800232618?pr=4165) and have this failing action. Can anyone offer some guidance as to going about fixing this?
unfortunately it's been frequently failing, it's not related to your PR
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
Got it, thank you.
also just commented on the issue
Thanks! This is probably OK but I left a comment on the issue.
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...
π
is it OK to ask about the ruff formatter here?
This channel is specifically for collaboration in the Black project, but you could ask in #tools-and-devops
if you want to, but it's not a great place. I think Ruff has its own discord server
ok thank you, appreciate the response and the direction
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!
This has been getting a little messy. These changes neaten things up, we don't have to keep guarding against self.previous_line is not None, we make it clearer what logic has side effects, we reduce the amount of code that tricky before could touch, etc
This change is intended to be a no-op
Thank you for all you recent PRs!
This looks great, thank you!
(technically this change does meet the stability policy, since it won't cause changes in already blackened code, but always nice to let things bake in preview...)
Thanks for making this happen!
This is out-of-date and just a chore. I don't think this is useful to contributors / can't matter to users since Black doesn't even have a public API.
Good call, I was thinking of removing this too
7d78946 Describe 2024 module docstring more accurately ... - hauntsaninja
Thanks, this looks good. I pushed a slight wording change.
time for 24.1
CHANGES.md if necessary?congrats!
the wheels aren't built yet π
are you blaming me for not making mypyc fast enough π
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)
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
https://pypi.org/project/black/24.1.0/#files we got our wheels
hooray!
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...
Describe the bug
Empty classes now format differently between black and what flake8 expects:
To Reproduce
class Foo:
...
Reformats with the latest black to:
class Foo: ...
Which then flails flake8 with:
E701 multiple statements on one line (colon)
Expected behavior
Flake8 and black should be compatible in accordance with guidance at: https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html...
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...
Describe the bug
It is impossible to use Black 24.1.0 alongside reorder-python-imports. Using the example from #1872 , reorder-python-imports produces:
"""Module docstring."""
import typing
While formatting with black and default arguments produces the following:
"""Module docstring."""
import typing
This new behaviour makes the two tools incompatible. The author of reorder-pytho...
Fixes #4172
CHANGES.md if necessary?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
Describe the bug
I originally posted on SO here.
I have a python project with Flake8 and Black installed. I'm using VSCode, with the following workspace configuration in settings.json: "black-formatter.args": ["--line-length=80"],. I also tried: "black-formatter.args": ["--line-length, "80"],
This arg is also manually addedin the settings UI for the ...
Makes sense to me and 32 chars is enough to be unique I believe.
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
Thanks, that's really interesting! Surprised 80 isn't more common
@henryiii shared some useful data on common Black configurations in pyproject.toml files found on PyPI. A few pieces of weirdness stood out:
line-length = "100". This is very rare, about 25 instances total out of almost 20k (~0.1%).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...
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...
"""
87 characters ............................................................................
"""
"""
87 characters ............................................................................
"""
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! π€)
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...
Thanks!
This will need to go in the preview style, so gated behind an if Preview... in mode check (you can see examples elsewhere in the code).
Thank you! Some nits and questions below.
Looks good. I'll fix the one minor issue, then hopefully diff-shades will succeed if I retry.
Describe the style change
Examples in the current Black style
def f():
"Make sure this code is blackened"""
pass
Desired style
def f(
):
pass
Additional context
1607e9a Fix missing space in option description (#4182) - JelleZijlstra
This directory gets created by a pre-commit check, so adding it to the ignores.
CHANGES.md if necessary?(I don't think any of these are needed for this change?)
79fc115 chore: ignore node_modules (produced by a pre-c... - henryiii
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.
CHANGES.md if necessary?CHANGES.md if necessary?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.
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 '\.'
:...
Hi Everyone I am looking at documentation to try contribute to the project. https://black.readthedocs.io/en/latest/contributing/the_basics.html
I have experience with codding, pull requests, debugging, PyCharm and etc. but new to Open source projects
I tried two black versions: black 24.1.1 and 23.3.0. Only the 23.3.0 version removes the REDUNDANT SPACE in the code below
if not best_rate:
# REDUNDANT SPACE
print(f"No match found for {phone_number}")
else:
print(best_rate)
I cannot find where this change is documented in the change log here
I would love to know if this change is intended and why. Thanks
8912a33 Bump peter-evans/create-or-update-comment from ... - dependabot[bot]
d6e11ca Bump peter-evans/find-comment from 2.4.0 to 3.0... - dependabot[bot]
Resolves #4173
Related to #3888
CHANGES.md if necessary?Thanks, this is good, but I think there's some larger areas of possible improvement. If you're up for it, please make these changes; otherwise we can merge this as is and leave the rest for another PR.
This is a quick fix followup to #4181 based on https://github.com/SchemaStore/schemastore/pull/3559. Any future changes needed to that PR will also be made here, either to this PR if still open or a followup.
CHANGES.md if necessary?Thanks, and sorry for missing this. I'll leave this PR open for a bit in case other minor issues come up.
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...
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.
Good point, I do think it might be annoying to maintain as we move features between preview and unstable. Maybe instead we should set a guideline to put the responsible preview feature in the issue title so it's easy to track
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.
Both edits can only be done by triagers or maintainers, but putting the feature name in the title has the advantage that it shouldn't change over time
I added the name of the relevant feature to all open preview style issues, and changed the label description to say the feature name should be added
I forgot there is an open crash with the hug_parens change (https://github.com/psf/black/issues/4036), that means we should move it to unstable
Also you're right that it might not be clear initially which preview feature is responsible, but we can always change the title later
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.
Primarily because of #4036 (a crash) but also because of the feedback
in #4098 and #4099.
CHANGES.md if necessary?This looks good! I think if you want pre-commit to work you have to do repo: local (and also probably avoid any non-stdlib deps)
cca3c0f Test that preview/unstable features are documen... - JelleZijlstra
Describe the bug
Comment in redundant parentheses gets removed accidentally.
To Reproduce
For example, take this code:
def return_true():
return (
(
True # this comment gets removed accidentally
)
)
And run it with these arguments:
$ black test.py
It removes the comment accidentally.
def return_true():
return True
Expected behavior
def return_tru...
@JelleZijlstra I've made the requested changes. My thought process:
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.E704 is already disabled by default, so #3888 actually didn't document it correctly. Fixed that here.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...
Describe the bug
After upgrading to the latest version, when I rub python -m black ., I got files reformatted:
Then, when I commit, it against reformat the files restoring them:
Irrational beha...
Thanks for working on this!