#black-formatter
1 messages ยท Page 2 of 1
huh, it in fact does, I have not expected that
Why would you expect that Black won't preserve CRLF?
I thought that a part of Black's style would be to enforce LF
Wow - Did I hit a GitHub bug or what from Airplane wifi ๐ฎ - https://github.com/psf/black/pull/3257
I am the king of finding weird bugs
GitHub not so friendly on slow high latency links
Python preserves both so I feel we should too right?
Just wonder if this could break any IDEs etc. using blackd
I don't understand this? Python is not a formatter?
Yeah, that was misleading. If you're on windows, and you make a text file with CRLF python can support it and a developers editor might need the CRLF so I thought we (black) wanted to preserve that
I'm not really suggesting that Black should normalize line endings to LF, though I am surprised that it doesn't do that already ๐
Python supports both single and double quotes but that doesn't mean Black shouldn't normalize it
We wanted to break less so I thought (and I could be wrong / not remember) that we wanted to preserve CRLF for Windows users ... but happy to be wrong
git takes care of that, so dev on Windows would be a bit awkward if Black didn't preserve them
I'd prefer we normalized to \n as a POSIX Unix/Linux guy
Yeah, I have 0 Windows skills/knowledge
Would it be awkward? Editors (even Notepad iirc) support both
So after formatting, it wouldn't really matter
Regardless, I find it odd how black preserves CR but blackd does not
git status will be off I think
Yes, blackd should do what black does
Makes me question the PR since it feels like it's overcomplicating something
As I said, I was just surprised that Black doesn't normalize to LF
That's fair, I guess that part of Black's handling is done later on (outside of the function used by blackd to format)
Probably, but I would like to figure out why before accepting the PR
Original decision to preserve whatever is there in psf/black#258 and my PR arguing for Windows style in our Prettier (but the point still stands for Black): psf/black#2244
is this about git status showing the file as having unstaged changes even when the only change is CRLF->LF and only after you git add it, git starts properly to ignore it while not actually staging the file since there's nothing to stage? :
autocrlf is kinda funky like that, just didn't feel like it's that big an issue
but yeah, fair point :P
How does one ignore this deprecation warning here? https://github.com/psf/black/runs/8193107001?check_suite_focus=true
It's a new one we can't remove until we pin (when it's released too) aiohttp >= 4.0 it seems but I've not been able to workout how to ad it to the pyproject.toml ๐
https://github.com/psf/black/pull/3198 there's an open PR for this, but it's been stalled as we were (unsuccessfully ๐ฆ ) trying to get a first-time contributor to work on this PR.
I can take over and get it merged now it's blocking work.
So I can't ignore it via the pyproject.toml pytest settings cause it's in aiohttp?
you can, but we also have to mitigate it in blackd's source code to not blow up when the decorator is removed from aiohttp
https://github.com/psf/black/pull/3198#issuecomment-1229258987 that's what this patch does in summary
Rightio โฆ seems a good path and saves us hard setting >= 4.0 right away and be ready for it
Iโll try look at it if you gone beat me. I had some time waiting for connecting flight home and now out of time.
I'm preparing a PR right now
annoyingly both mypy and flake8 really hate the changes I initially suggested
I wish aiohttp did more minor release more often
So many changes on GitHub vs PyPI version
I wished they released more often too
there are so many deprecation warnings, gah, it was confusing to test my patch because I was running into upstream deprecation warnings about deprecated loop arguments
it works though, will submit the PR now!
Awesome.
Description
This is deprecated since aiohttp 4.0. If it doesn't exist just define a no-op decorator that does nothing (after the other aiohttp imports though!). By doing this, it's safe to ignore the DeprecationWarning without needing to require the latest aiohttp once they remove @middleware.
Resolves GH-3176. Closes GH-3198.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- [x] Add / update tests if necessary?
- [x] Add new / update outda...
Thanks! Iโll try rebase and retest 3.11 later!
Youโre quite the typing guru these days.
062e644 Mitigate deprecation of aiohttp's @middleware... - ichard26
Looks great to me, thank you so much @cooperlees! Enjoy your flight! :airplane:
Cool
Does anyone know if there's an issue for the lack of parens on a split in the second argument here:
https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AEJAJZdAD2IimZxl1N_WlbvK5V9KPuirYHMOSnscXUo6FAlZJ5GBmWLlbVpyBkkx4ZLxSl9Llvkk47zK7EX4f8PmaejwtpdWrsfot1u7Kua5ORlmm8Y6C2R8wucMaR7k5Za19BpLQMs8nqRfYFbsrs03mcCTxWM3lrHw_AMdIdBRcjtXFbpwiSpnf2QhhYZ-_cMTQK3lCP8rizBAAAAAO9cX91ud66GAAGyAYoCAAAizVcoscRn-wIAAAAABFla
Playground for Black, the uncompromising Python code formatter.
Describe the style change
Original code:
function_call(
(
" 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 ullamco laboris nisi ut aliquip ex ea commodo",
)
Examples in the current Black preview style
black --preview removes the parens since they are "not necessary":
functi...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Description
Fixes #3261.
When LL[0] is an atom string, we need to check the atom node's siblings instead of LL[0] itself, e.g.:
dictsetmaker
atom
STRING '"This is a really long string that can\'t be expected to fit in one line and is used as a nested dict\'s key"'
/atom
COLON ':'
atom
LSQB ' ' '['
listmaker
STRING '"value"'
COMMA ','
STRING ' ' '"value"'
/listmaker
RSQB ']'
/atom
COMMA ','
/...
Not good on mobile
yeah coz the logo is so huge
I'll try and do something about it
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Is this related to a problem? Please describe.
The pages on stability policy and GitHub Actions are very clear. However, I don't think it's possible to enforce stability with GitHub actions.
Describe the solution you'd like
I would like to add uses: psf/black@2022 in my GitHub action, and have this be equivalen...
Description
Addresses the lack of support for version specifiers in GH action that was mentioned in #3264.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- I think there aren't any
- [ ] Add new / update outdated documentation?
- I'll do it soon:tm:
without this, the script fails if any commit contains non-text files
Thanks. why not. TIL too ...
Will leave it for a little bit to give some other people the change to review / question.
@bright glacier sorry for the ping, can you let me know once you have some free time?
you're likely to get better help if you ask your question and let them answer in their own time
Hi what do you need? Is it a PR you want me to review and merge?
i thought about it but since it is a bit offtopic for this channel i was going to open a help channel for it
oops no sorry,its something more related to mypyc
I have some free time right now, feel free to open a help channel
currently in a class but as soon as im free i'll open it
Describe the bug
File failed to format. Both the file and diff are attached to this message.
Error present in both newest version of black (used pip install --upgrade black to make sure) and [online formatter] (https://black.vercel.app/?version=main).
Environment
Operating system: Linux (xubuntu 22.04 64bits)
Python version: 3.10.4
black.__version__ == '22.8.0'
The resulting error
running black main.py produces the following error:
error: cannot fo...
I'm busy now. Sorry.
No problem; i think I figured it out, I was running the module directly instead of importing
how to make black not fail in pre-commit when it modifies?
pre-commit only runs against the code in the staging area. When black (or any pre-commit hook that auto-fixes your code) fixes your code, you must then add that code to the staging area (using git add), then the next time you try to commit it will pass.
pre-commit takes a strong stance on never modifying the staging area, you can read about it here https://github.com/pre-commit/pre-commit/issues/747#issuecomment-386782080
Also called.. a script? ๐
Hi. I've poked around the black codebase a few times. I'm writing a formatter for Jinja strings and one of the goals is to follow black's style for any of the pythonic bits. I can't use just black, because there is plenty of jinja-specific syntax I'm working with.
So, my question: how does black decide where to add new lines? Is there a particular place in the codebase I can look at to see more about line wrapping?
LineGenerator maybe? https://py.wtf/black/black.linegen/LineGenerator
@cosmic topaz
Ah yes thank you. And I see the transformers that handle aspects of reformating. Thanks!
Thank you for the PR! The code makes sense to me ๐
LGTM (although I didn't test this, I hope there isn't a bug somewhere). Thank you very much!
How do I make black to ignore a file. Any prefix like something I need to put on top the file for that??
using #fmt off in vscode, resolved
Describe the bug
Black in some cases put the wrong parts on separate lines when having a trailing comma.
For example this:
assert foo(1, 2, 3,)[
0
] == {'bar': 'baz'}
Expected result was something like:
assert foo(
1,
2,
3,
)[0] == {'bar': 'baz'}
To Reproduce
Minimal example:
a = [1,][2]()
b = [1,][2](3)
Expected:
a = [
1,
][2]()
b = [
1,
][2](3)
Actual result...
Interesting
It seems that a combination of incorrect formatting and the presence of an incomplete f-string produces a parsing error. The interesting issue is that the error is not raise when the formatting is correct.
I think this is best explained by an example.
This raises a parsing error ("cannot use --safe with this file; failed to parse source file."):
non_capitalised = {
c: lowercase_map[c]
for c in columns if (c.lower() in lowercase_map and c not in expected_cases)
}
if...
Minor question about stability policy (https://black.readthedocs.io/en/stable/the_black_code_style/index.html). It mentions the following.
"If code has been formatted with Black, it will remain unchanged when formatted with the same options using any other release in the same calendar year.
This means projects can safely use black ~= 22.0 without worrying about formatting changes disrupting their project in 2022."
My understanding of ~= 22.0 is that it allows only the patch updates as >=22.0 <22.1
In order to allow even minor releases during the year, should the dependency be ^=22.0, that is >=22.0 <23.0?
!pep 440 -- according to this, ~= 22.0 is (mostly) equivalent to >= 22.0, == 22.*
>>> from packaging.specifiers import SpecifierSet
>>> s = SpecifierSet("~= 22.0")
>>> s.contains("22.0")
True
>>> s.contains("22.1")
True
>>> s.contains("22.0.1")
True
>>> s.contains("22.9")
True
>>> s.contains("23.0")
False
yup.
yeah, more specifically it replaces last digit with a wildcard so i.e. ~= 22.0.0 would mean >=22.0.0, == 22.0.* while ~= 22.0 means >=22.0, == 22.*
I appreciate the follow-up!
72a2559 [FIX] migrate-black.py: don't fail on binary fi... - hbrunn
The two messages there seems a little spammy
I don't really mind to be honest
If we had to remove one, I'd kill the new commit one though
It's been a while since I've last reviewed a PR[^1], but this looks great, thank you!
[^1]: about that, I'm incredibly busy lately with personal matters unfortunately.
e2adcd7 Fix a crash on dicts with paren-wrapped long st... - yilei
@half meteor and whoever is following this channel, I had around 25 minutes to spare tonight hence the activity. I'm not sure when I'll have more time, but I promise I haven't forgotten your work / PRs!
how dare you have [life stuff to deal with]
seriously though, you're doing great job with this project, it's fine to have other things to do ๐
especially in entirely voluntary project
absolutely no worries on my PRs, personal life takes much higher priority than open source. thank you as always for the work ๐ค
Description
These two paragraphs were tucked away at the end of the section, after the diversion on backslashes. I nearly missed the first paragraph and opened a nonsense issue, and I think the second belongs higher up with it too.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
A changelog entry is unnecessary, I believe. - [x] Add / update tests if necessary?
N/A - [x] Add new / update outdated documentation?
Yes
Black documentation used to contain a section on how to use Black with PyCharm via a file watcher utility.
Now there is no mention of this option of using Black, only though a third party plugin AND some more dependencies.
There might be reasons why I don't want or can not install other dependencies, for example aiohttp or PyCharm extensions that is required for Black[d]
Describe the solution you'd like
Add a documentation section on how to use Black with PyCharm file...
Hi, I came here after reading that sublack is no longer being maintained, however it is still the recommended sublime plugin for black. Does anyone here have a recommendation for a sublime plug-in for black that is being maintained?
You can use SublimeLSP
And then use pylsp with that
Or you know, you could just continue using sublack because it works just fine
Unless there's something in particular that doesn't work for you and you actually need an alternative
I'm using sublack right now and personally don't see why I would even need the plugin to be maintained, it serves my purposes and Sublime Text's plugin APIs are quite unlikely to change in incompatible ways in this decade.
Thank you, this makes much more sense!
04bce6a Improve order of paragraphs on line splitting (... - TomFryers
@VictorStinner @sethmlarson I think my favorite feature of Black is that almost everyone on a team has one or two nitpicks/annoyances about how Black formats something. "Oh ya, the way it does {x} is annoying" and then we all go about our day. Perfect.
The mypyc build requires gcc to be installed even if it's being built with clang, otherwise clang fails to find libgcc.
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
SGTM - Not a big deal, but can we just install libgcc? if the check needs gcc that ignore me :)
Bug description
Changing line lengths is not reversible because Black adds a trailing comma to some argument lists.
To Reproduce
def some_fn(*args):
pass
some_fn(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
Reformatting with --line-len=20 results in
def some_fn(*args):
pass
some_fn(
1,
2,
3,
...,
20,
)
Unfortunately, due to the trailing comma after the 20 that wasn't there before, re-black-ing ...
Description
Noticed a typo in line 18, all calls to make_context_manager() had the number outside of parentheses. Changed "make_context_manager1()" to "make_context_manager(1) ," for all four calls.
Description
This shouldn't be necessary, but in practice macOS also requires freeze_support() so let's play it safe and always call it when sys.frozen is truthy. Only a tiny sliver of users will be using these PyInstaller executables and the start-up performance is already terrible as the executable unzips itself on the fly anyway.
Fixes #3250.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update ...
Currently working on getting mypyc wheels to build on 3.11 via CIBW
Mildly annoyed that myst-parser still hasn't published a new release with docutils 0.19 support
OK attempt two at writing a status update on 22.9.0 (because I accidentally pressed Ctrl-R while writing it):
- I'll review the hatchling PR and then the "autodetect target-version using project.python-requires" PR soon
- I will probably not review the blackd PR anytime soon as I honestly do not care, feel free to merge it without my review
- I filed PRs to both fix the broken macOS executables and start building mypyc wheels for CPython 3.11
- I'm planning to resolve the merge conflicts in https://github.com/psf/black/pull/2996 and land it if no one objects
Regarding the hatchling PR, it already looks good, but I'll take one more look to hopefully make sure it's alright. I'm a little worried for the downstream redistributors of Black that aren't using PEP 517, but I don't know how to reach out to warn them in the first place :/
Description
Bumps cibuildwheel from 2.8.1 to 2.10.0 which has 3.11 building enabled by default. Unfortunately mypyc errors out on 3.11:
src/black/files.py:29:9: error: Name "tomllib" already defined (by an import) [no-redef]
... so we have to also hide the fallback import of tomli on older 3.11 alphas from mypy[c].
Closes #3224.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update...
out of pure curiosity, do you still have plans to move to nox (since you'll be dropping 3.6 support in this release)
nope.
not at all or just not now?
if we're going to change our project automation, it's probably towards hatch
not that that's going to happen anytime soon as I'm the only one working on developer UX and well, I'm pretty busy
but yeah, this is just pure curiosity since you were thinking of doing that some time ago and got blocked by the 3.6 drop by nox
Awesome, thank you! It's embarrassing that I missed this when I reviewed the PRs that added these examples ๐
Not sure if i'm doing something wrong, but trying the example in black it seems that it isn't formatted at all:
(I tried it with a couple different combinations of settings and none seemed to do anything)
Playground for Black, the uncompromising Python code formatter.
Black doesn't format context managers yet
The above is a document about future style
You actually can't parenthesize context managers before 3.9 (provisionally) and 3.10 (stable)
there were plans to use \ for splitting them on lower versions but I'm not sure that's still planned considering newer versions support splitting it without backslashes
but yeah, all of this is about future style, afaik it hasn't been implemented yet into the --preview style either
Ahh, that makes sense, thanks
This is correct.
Hello. May I ask how to use hotkey to auto lint with black?
I set it up while ago, but I forgot to mark up the steps of how to make it
What editor / ide are you using?
vs code
https://code.visualstudio.com/docs/python/editing#_formatting and then search the vscode keyboard shortcut settings for "format document" and change the keyboard shortcut to whatever you'd like
I don't have access to an instance of Visual Studio Code so I can't really provide anything more specific than that right now, sorry!
That looks good assuming black is available in the active python environment
IIRC the shortcut is Ctrl-I or Ctrl-Shift-I
Is that the expected behavior of linting? not used while ago.
I expect it should correct all of it automatically
That's not black at all. Sorry I didn't realize the misunderstanding earlier.
Black is not a linter, it's an autoformatter so it simply reformats code (changing whitespace, linebreaks, parentheses, etc.)
yes
Pylance and flake8 are linters, but they don't have any autofix functionality as far as I know
?
The first two was already enabled but it is not work
And now I enabled the third one
what happens when you press shift-alt-F ?
yeaaa, your python code is invalid, black won't be able to format that
can't remember if the python extension emits an error if black fails
ah it does not
so i might used autopep8 as the default auto linter before. vscode still lints correct lines before
What do you mean by linting? Black is never going to raise any warnings or errors in the messages tab, it's not a linter.
(autopep8 is also not a linter FTR)
I would be incredibly surprised if autopep8 has error recover and can format only the parts of a file that are syntactically valid, ignoring the broken bits
formatter
I know that. What you're saying isn't making sense to me. What do you mean by "vscode still lints correct lines before" ?
and by the way this is why black isn't doing anything, the code after the with statement is improperly dedented and the second comma in the dictionary literal should be a colon instead.
That's not really accurate either. While some warnings / errors linters raise may be fixed by autoformatters (usually ones about style, see the F prefixed flake8 errors), that's more a happy side-effect / accident
linters and formatters are very different, they can have overlapping goals (deal with code issues, whatever they may be) but their approaches are very different and so are their domains
linters usually only detect and warn, there are probably some linters with autofix functionality but flake8 is definitely not one of them. anyway linters also go beyond just code style, they might warn on unsafe code (e.g. bandit), type issues, overly complex code, etc.
formatters are laser focused on the code formatting / style, they shouldn't affect the logic or execution of the code
not quiet understand. But you did a very good job of explaining the concept. I think I have 90% understanding now, thanks ๐
(tools that automatically change the logic or execution of a program might be called optimizers or refactoring tools depending on what they do, but not formatters AFAIK)
All sounds good to me! Thanks.
@bright glacier I can't get those ARM wheels to download
crl-m1:tmp cooper$ wget https://github.com/ichard26/black-mypyc-wheels/suites/8342284497/artifacts/367142266
--2022-09-18 16:10:55-- https://github.com/ichard26/black-mypyc-wheels/suites/8342284497/artifacts/367142266
Resolving github.com (github.com)... 64:ff9b::c01e:ff71, 192.30.255.113
Connecting to github.com (github.com)|64:ff9b::c01e:ff71|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2022-09-18 16:10:55 ERROR 404: Not Found.
Tried safari too - Will try chrome
Ok - seems chrome worked. lol
lol wat
I would've thought the download link expired, not that it only works on chrome ๐ฅด
3.10 wheel worked
I don't have 3.11 installed on my M1
Can we scope # fmt: off such that it re-enables automatically after coming out of scope?
Or is there like a fmt_off decorator to mark functions that should not be formatted?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Is your feature request related to a problem? Please describe.
I'm trying to setup a GitHub Action that runs Black on a project that includes *.py and *.ipynb files, but the default action does not include the Jupyter extra. I followed the integration described in this piece of documentation but the option to include the Jupyter extra (black[jupyter]) is not available.
Describe the solution you'd like
...
Description
This PR fixes #2567, #3184, #2985, #2882, #2232, #2140, #1817, #569. Previously Black produces invalid code because the # fmt: on is used on a different block level.
While Black requires # fmt: off and # fmt: on to be used at the same block level, incorrect usage shouldn't cause crashes.
The formatting behavior this PR introduces is, the code below the initial # fmt: off level will be turned off for formatting, when # fmt: on is used on a dif...
oh gosh, it's september 22 already ๐
I really need to finalize the most critical parts of this release this weekend (I should be free ๐ค )
(please ping response)
is there an official black formatting api, for me to use instead or still a weird workaround or not right now?
no updates since we last spoke, sorry
okay, hopefully one comes out soon
Actually I have a weird question
so I run it the util in run_in_executor
right now, but can I do this in an asyncio.create_thread()?
should be ok though I haven't tried it
it's possible you'll run into issues if you try to format multiple files at once
if black's multiprocessing interacts poorly with asyncio
Sounds like we should test this tbh
@bright glacier ```jelle@mbpt-root pyinstaller % git grep freeze_support
PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py:def _freeze_support():
PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py:multiprocessing.freeze_support = spawn.freeze_support = _freeze_support
they monkeypatch it ๐
so it does indeed do something on macos
so the CPython docs aren't wrong , but just useless a lot of the time, sigh.
I guess if you used cx_freeze, the docs would be right since it doesn't even support macOS or Linux
maybe add a comment to the code about this monkeypatching and then we can land your PR
Description
Adds support to enable formatting of Jupyter Notebook files in the GitHub Action integration. See https://github.com/psf/black/issues/3280 for more information.
Closes #3280
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] ~Add / update tests if necessary?~ No relevant tests found
- [ ] Add new / update outdated documentation?
Black translates this code:
[
# fmt: off
"foo1", # comment1
"foo2", # comment2
# fmt: on
]
into this:
[
# fmt: off
"foo1", # comment1
"foo2",
# comment2
# fmt: on
]
but shouldn't change anything at all.
Environment
- Black's version: 22.8.0
- OS and Python version: [Linux/Python 3.8]
Minor typo
Description
Checklist - did you ...
- [x ] Add a CHANGELOG entry if necessary?
- [x ] Add / update tests if necessary?
- [x ] Add new / update outdated documentation?
I don't like how the entire paragraph is phrased to be honest, but this is an improvement over the status quo, thank you.
I will also note this typo probably also exists in docs/index.md.
whooooo
Wow
why black formater why not white formater
why not?
the name is a play on the quote "any color you like, so long as it's black" by henry ford (paraphrasing)
Description
Just a very small quality-of-life change. Clicking the big Black logo in the README will now take you to the documentation page, as opposed to just taking you to the logo file.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Let's ship it! :ship:
Thank you so so so much for the PR and all of the patient waiting. I know I took way too long to review and eventually approve this, I'm sorry about that. You shouldn't have to wait so long.
i finally did a thing
I will admit I'm nervous changing something as low-level as the build backend, but the Python packaging ecosystem is reasonably modern now, hopefully?
Might be worth clarifying that jupyter is a boolean option so people don't expect 1 or yes to work, but otherwise this looks great. Thank you very much!
Congrats on your first PR here! Feel free to add yourself to the AUTHORS list :)
@austere lava @red sedge if you want to, you can now clean up our asyncio code now that Black requires Python 3.7+
I also missed the accidental removal of the 3.11 classifier in the PR :sweat:
pyupgrade likes to add optimizations re. comprehensions ยฏ_(ใ)_/ยฏ
I'm always a bit leery about those because I feel like the listcomp version is likely to be usually faster in practice. But I think mypyc compiles genexps as listcomps anyway ๐
Yup, mypyc does convert genexprs to listcomps anyway :)
The timing on my freeze_support() PR haha ๐
did I just beat you on the merge?
yup, I was confused at why it did nothing
๐
Description
I resolved the merge conflicts in #2996. This PR is that PR with a few tweaks on top.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
holy crap, I did not expect so many upvotes on psf/black#3214
Yes?
https://github.com/ichard26/black-mypyc-wheels/actions/runs/3131271649/jobs/5082438101 and CIWB is failing, again. My goodness.
ModuleNotFoundError: No module named 'hatchling'
Not sure why it's not happening on Linux
I also swear the Hatchling PR was working before I merged it 
According to the logs, it's just refusing to install the build-system dependencies before calling prepare_metadata_for_build_wheel?
like it's skipping straight to "preparing metadata ..." for some reason
I give up, I have other work to do.
Description
I believe most users would not want to run black[jupyter] on files in .ipynb_checkpoints/.
This PR adds .ipynb_checkpoints/ to DEFAULT_EXCLUDES in src/black/const.py
I did a quick issue search and couldn't see if a PR like this is outside of scope or has been rejected in the past (https://github.com/psf/black/issues?q=is%3Aissue+ipynb_checkpoints)
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if neces...
why is black's output different for:
import os
import requests
```and```py
import os
import requests
shouldnt one of the them be changed to the other since they are the same (pretty much) or does black allow the user to choose the amount of lines they want?
Is your feature request related to a problem? Please describe.
I was working on a project that is only intended to run on Python 3.10. However, the black configuration incorrectly listed multiple target versions because I copied the file from a different project.
When I tried to format a file with a match statement, the error was
error: cannot format foo.py: Cannot parse: 2:6: match bar:
I was initially confused as I knew that black had added Python 3.10 support. Then I...
Description
While working on my first PR it took me a moment to figure out where the CHANGELOG can found.
This PR makes the location more explicit which hopefully makes PR smoother for other first time contributors.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Examples in the current Black style
def some_fastapi_route(
some_header: str
| None = Header(
None,
some_helpful_description="Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn",
),
):
...
Desired style
def some_fastapi_route(
some_header: str | None = Header(
None,
some_helpful_description="Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn",
),
):
...
**Additional...
black sort of lets the user choose how much vertical whitespace they want. very early versions of black were strict about this and it ended up being one of the things black needed to be a little more flexible on
Thank you, this is great. I love removing pain points from the contributing experience :)
096806e Mention CHANGES.md in PR template explicitly (#... - raybellwaves
ddb9924 Bump pypa/cibuildwheel from 2.10.0 to 2.10.2 (#... - dependabot[bot]
No idea how this survived, but it is no longer useful and is actively breaking the build.
Description
Adds a new CLI option to skip the first line of source code while formatting. To enable use the -x/--skip-source-first-line flag. The skipped line will be retained in the output. The option is also available for blackd.
Closes #3214
Checklist - did you ...
- [X] Add an entry in
CHANGES.mdif necessary? - [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
Description
Adds a new CLI option to skip the first line of source code while formatting. To enable use the -x/--skip-source-first-line flag. The skipped line will be retained in the output. The option is also available for blackd.
Closes #3214
Checklist - did you ...
- [X] Add an entry in
CHANGES.mdif necessary? - [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
To Reproduce
Unformatted code:
def main():
if a:
# Comment
def b():
pass
Running black --preview:
def main():
if a:
# Comment
def b():
pass
Expected behavior
It does not remove the empty line:
def main():
if a:
# Comment
def b():
pass
Additional context
I did a bisect and this was caused...
Describe the style change
Black 22.8.0 makes typing hints in Python โฅ 3.10 harder to read by line breaking on the pipe (type union) operator without any apparent reason.
Examples in the current Black style
I'm writing a FastAPI application:
from fastapi import APIRouter, Query
router = APIRouter(prefix="/black", tags=["black"])
@router.get("/foo")
async def foo(
param1: str
| None = Query(
default=None, title="A parameter", descript...
Description
Enforce empty lines before classes/functions with leading comments:
- Fixes #246
- Fixes #3300
EmptyLineTracker works on lines that haven't been split yet. When sticky leading comment is used before class/def lines, the tracker must look behind the possible comment lines. So I introduced a new LinesBlock class to keep track of those states.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if ...
Thank you for the PR! I know almost nothing about Jupyter Notebooks, you learn something new everyday :)
hi there. anybody know if there's ongoing work on formatting multiple "with" statements as described here https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html?
I don't think so
I always wanted to work on that, but I've never had the time to commit to another major project like that.
welp.
i don't understand this change
@property
def cog(self) -> Optional[Cog]:
- """Optional[:class:`.Guild`]: Returns the guild associated with this context's command. Returns ``None`` if not available."""
+ """Optional[:class:`.Cog`]: Returns the cog associated with this context's command. Returns ``None`` if it does not exist.
+ """
imo it does not make the code easier to read
i might be in the minority but i really dislike docstring touching
like
it arguably looks worse having the """ all alone on a line with the entire docstring before that
only considering the 3.9+ case using parens, how big a project is this? my understand is that the parser already supports it (along with the match statement), and if you manually add parens, it already formats nicely.
so the thing left to do is to add parens? if this is correct, I might be able to spend some time on the 3.9+ part
b1077aa Bump myst-parser from 0.18.0 to 0.18.1 in /docs... - dependabot[bot]
980997f Bump furo from 2022.9.15 to 2022.9.29 in /docs ... - dependabot[bot]
1a20c4d Bump sphinx from 5.2.1 to 5.2.3 in /docs (#3305) - dependabot[bot]
When a docstring is formatted using markdown, an extra space at the end means that the next line is not to be wrapped. (pydoc3 uses markdown). Unfortunately, black removes the extra space, which causes markdown renders to not do what they are supposed to.
Example code that gets miss rendered. Note: I am using a _ to denote a space at the end of the line.
Original
def boo():
"""Halloween.
This is not supposed to be wrapped._
New text
"""
After ...
Description
This implements #3292.
I have only heard one ๐ from @felix-hilden. But I think it's also easier to decide after seeing the formatting changes introduced by this PR, thus I'm sending it now so we can visualize the diffs.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
@dense jungle i can't find an issue reporting this but i don't want to make a duplicate so i thought i'd ping you before proceeding
I'm pretty sure we made this change on purpose in some PR
yeah, psf/black#3044
although it seems like a bugfix that affects everyone else who wasn't affected by the bug
scrolling through https://github.com/psf/black/blob/main/CHANGES.md doesn't actually tell me which pr implemented that
it seems to be a side-effect of a bug fix and isn't mentioned directly in any of the Preview Style changelogs
was a change between 22.3.0 and 22.6.0
that pins it down to these
it looks to be this one:
Docstring quotes are no longer moved if it would violate the line length limit (#3044)
which reading it again sounds right, but i can see a different way it could be worded
Docstring quotes that would violate the line length limit now follow behind a single-line docstring
i can also see that it's an awkward format and that sometimes that second line behind a docstring matters a lot
the issue i have with this fix is that there's two other ways that aren't touched at all
# leaves this as-is
"""
Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has."""
# leaves this as-is too
"""
Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has.
"""
``````py
# but provide this...
"""Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has."""
# ...and it turns into this:
"""Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has.
"""
+1 to not moving the trailing quotes in the last example
especially given it's not moved in the first example above
Is your feature request related to a problem? Please describe.
As a new user of black, I installed the black package from my distribution to try it out. After that, I wanted to integrate it into vim. I set up the plugin, but discovered that the plugin requires building a virtualenv within which to install black. Using a virtualenv is undesirable to me for the following reasons:
- I already have black installed; there should be no need to install it again.
- The virtualenv adds clut...
Provide a configuration parameter to the Vim plugin which will allow the plugin to skip setting up a virtualenv. This is useful when there is a system installation of black (e.g. from a Linux distribution) which the user prefers to use.
Using a virtualenv remains the default.
Description
I have several reasons why using a virtualenv is undesirable to me. I have listed them in the following feature request.
Fixes: https://github.com/psf/black/issues/3308
Checklist - did yo...
Describe the style change
The main use of semicolons in Jupyter Notebooks is to hide the output of some function calls.
Examples in the current Black style
import seaborn as sns
ax = sns.scatterplot(
x=df["tenure"],
y=residuals,
)
ax.set_ylabel("Residual")
After executing a cell with the code above, 2 things are outputted:
Text(0, 0.5, 'Residual')- The graph itself.

I really hope the release CD doesn't break
I'm waiting for https://github.com/psf/black/actions to finish and then we'll see ๐
although I might release typing-extensions first
I've fixed so many issues I feel like it shouldn't find a way to break by now, but automatic C compilation can be pretty thorny.
here we go
well the mypyc jobs haven't immediately crashed, that's a good sign
how long are they expected to take?
at most 30 minutes according to this test run a while back: https://github.com/ichard26/black-mypyc-wheels/actions/runs/3148043951
huh one failed https://github.com/psf/black/actions/runs/3200959148/jobs/5228453985 saying the file already exists on pypi
the arm64 workflow actually uploads x86_64 wheels https://github.com/psf/black/actions/runs/3200959148/jobs/5228454073
thanks, the universal2 workflow also uploads x86_64 wheels
https://github.com/psf/black/actions/runs/3200959148/jobs/5228454073#step:3:229 huh, CIBW is configured properly
does hatch not support cross-compilation?
maybe macos_arch is wrong? I started looking at cibuildwheel docs
@tender drift hi does hatch support cross-compilation to macOS ARM and universal2?
I'm going to feel like a massive idiot if hatch does not.
hm I can't find docs that say "macos_arch" does something
@bright glacier hatch-mypyc just calls setuptools
ah okay so it should work, I guess the cross-platform configuration is being dropped somewhere
perhaps using build as the frontend instead of pip could fix this?
I'll need to take a look at the CIBW code to have any clue though
I have to go now, but I'll take a look when I have more time
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
lol we actually did build amd64 wheels, they're just labeled x86_64
I'll just delete the macos wheels from pypi until we sort this out
sounds good
done
Description
The https://github.com/psf/black/releases/tag/22.10.0 removed runtime support for EOL Python 3.6. ๐
We can remove a few old checks and config.
Updating the mypy config means we can remove a couple of # type: ignore.
Checklist - did you ...
- [n/a?] Add an entry in
CHANGES.mdif necessary? - [n/a] Add / update tests if necessary?
- [n/a] Add new / update outdated documentation?
b60b85b Remove redundant 3.6 code and bump mypy's pytho... - hugovk
First of all currently it is not possible to use straight sphinx-build command to build documentation out of source tree
+ /usr/bin/sphinx-build -j48 -n -T -b man docs build/sphinx/man
Running Sphinx v5.2.3
/usr/lib/python3.8/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.17.1-unknown is an invalid version and will not be supported in a future release
warnings.warn(
Traceback (most recent call last):
File "/usr/lib/python3.8/site-p...
yeaa, at least this issue is not unreasonable
I generally don't like sys.path shenanigans but for docs, it's a lot more acceptable
This is the wrong channel for getting general python help (see #โ๏ฝhow-to-get-help ) but you're missing a colon on the if line
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
Using version specifier in GitHub Action fails. I believe this is because the stable branch has not been updated.
To Reproduce
Add the following GitHub Action to your repo:
name: Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: psf/black@stable
with:
options: "--check --verbose --skip-magic-trailing-comma"
version: "~= 22.0"
...
I'm looking for a way to remove the trailing comma check. When creating lists and dictionaries, the trailing comma as a style choice should be optional NOT required.
I've been leveraging the TOML configuration file as part of the Super-Linter project and Black doesn't seem to honor any of the configuration I am trying to enforce.
Describe the solution you'd like
I'd like a descriptive document around what syntax is expected for the TOML file.
**Describe alternatives you've con...
Thanks for the PR, some comments below!
The stable branch is automated, but since release CD failed, it wasn't updated. Perhaps it is indeed better to only gate it on the sdist + pure wheel job
Thanks a ton! Some comments below, and one discussion point: would it make sense to consider the comments to be in the block? Instead of having an outer "semantic comment" I'm not 100 % sure, but that could simplify things so that we can use ordinary newline rules for the whole block. Maybe? ๐ค
Describe the bug
When I try to use vim to run Black, I get the following message:
Error detected while processing function black#Black:
line 10:
Traceback (most recent call last):
File "", line 1, in
File "", line 143 in Black
TypeError: __init__(): got an unexpected keyword argument 'preview'
Press ENTER or type command to continue
This happens when calling :Black from a python buffer and then the code does not format.
To Reproduce
Use this `...
:incoming_envelope: :ok_hand: applied mute to @long shuttle until <t:1665340032:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).
The <@&831776746206265384> have been alerted for review.
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
unreachable code in src\black\parsing.py:170:
raise AssertionError("INTERNAL ERROR: Tried parsing unsupported Python version!")
Expected behavior
not having unreachable code ๐
Description
improve parsing error message to make sure users know which version it was run on (fixes #3294).
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Description
improve parsing error message to make sure users know which version it was run on (fixes #3294).
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Never a thing
Also good gosh Black has been active in the past 24 hours
darn
really should be
it's not too hard to implement, I might be able to do it without breaking the blame, too
I would've just created a sphinx plugin, but fair enough lol
there is a sphinx plugin in which you can use :anytexthere:`anythinghere` and it'll make a link
often used as :issue:`123`
and I'm pretty sure said plugin is bundled with sphinx
Talk to you later
Yup I know, that was what I was expecting you to suggest :)
there's also a replace syntax built in to sphinx parsing which occurs before giving the files to extensions
Heya! I want to set up black to format my projects in pycharm
Anyone know how to do this so it'll work for every project when I create it?
Describe the style change
When an import line is too long, and it only has a single imported symbol, it's more readable to NOT wrap the line.
Examples in the current Black style
from company.organization.products.my_awesome_learning_system.backend.handlers import (
register,
)
from company.organization.products.my_awesome_learning_system.common import logging
from company.organization.products.my_awesome_learning_system.utils import (
authent...
psf/black#2087
Description
I used the Black github action workflow in one of my projects and passed arguments via options. Because I had initially omitted '--check', my workflow did not fail, although Black found files that needed formatting. I would like to suggest this one sentence that makes that even clearer. It would have saved me some debugging time, as I am quite new to GitHub action workflows.
Clarifies ...
Description
PEP 621 requires the license field to be a table with either a file or text key: https://peps.python.org/pep-0621/#license
The current value of license = "MIT" is not PEP 621 compliant, even though hatchling allows it.
Description
Fixes #2551
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Good catch! Feel free to add yourself to the AUTHORS list :)
I agree and approve this extra addition. I feel it's too late now, but we should have probably defaulted with --check.
Should we think about a Major version release changing this default in the future? What are the downsides people see other than helping people find unformatted files?
Let's just please our prettier formatter on this markdown file please.
1c786ee Add support for named exprs inside function cal... - isidentical
d923945 Fix license metadata to follow PEP 621 (#3326) - amyreese
does black support plugin? I want to use it for airflow dags.
what do you need a plugin for?
relevant for scripts/diff_shades_gha_helper.py:
https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
Description
fixes #3321 (explained there).
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
A long line is split into multiple lines if it exceeds the black_line_length setting.
How to not take the comments into consideration to compute the line length?
Example:
# this one should still be broken into multiple lines
long_function(param_1="this is a long line, longer than 80 characters", param_2="this is a long line, longer than 80 characters") # comment here
# this one SHOULD NOT be broken because the code is smaller than 80 char
short_function(para...
I have this code:
def function():
from . import something_long_long_long_long # pylint: disable=import-outside-toplevel
black formats it to:
def function():
from . import (
something_long_long_long_long,
) # pylint: disable=import-outside-toplevel
This breaks the Pylint pragma, it does not work anymore on the line where black has put it. So, I played around with the pylint and black pragmas to get it working:
def function...
hi everyone, I just joined Discord, nice to meet y'all. Started using black formatter in my project. Wondering how to the make the imports absolute, automatically from vscode's intellisense?
I mean, if I have a function defined in this file - project/lib/utilities/file.py#readFile(path: str) , and when I try to import this function into some other .py file, I simply type readFile(...), and when I try to take vscode's help to automatically add the imports, it's just adding from utilities.file import readFile.
Is there a way I can have the automatic import use full paths instead? like from project.lib.utilities.file import readFile ? TIA
(P.s: also not sure if this questions should be asked to black or vscode ? let me know if this doesn't belong here please, I can check with vscode's peeps)
We don't change imports, VSCode might be a better bet! Or I've turned auto imports off, prefer to write them by hand because they sometimes are entirely wrong
gotcha. Thanks Felix, will check with vscode
bug caused by black: https://github.com/python/mypy/pull/13887/files
is this an old bug in black? can't seem to reproduce it in latest version
it's not a bug. they were matching on quotes in the code and black changed the quote style
I mean it's not a bug in black
ah, got it
black#3320
i'm a bit surprised that there wasn't a discussion on it ๐
since i'm not sure my proposed solution is the best
psf/black#3320
I'm okay with adding --check to the argument list unconditionally starting with 23.0.0.
Fantastic work overall! Your tests are great and your code was easy to follow. As mentioned earlier, I do have a few stylistic critiques and suggestions to make the logic more robust.
Also two general comments:
- Should we emit a message telling the user what we inferred the target version to be as part of
--verbose? - By inferring a default for
--target-version, Black will never do per-file auto-detection ifproject.requires-pythonexists and is valid. This is certainly better ...
Oh man that took ... like an hour to review ๐
I didn't even notice how much time had passed, that's how focused I was.
Thanks for submitting this, look good apart from a changelog detail ๐
Let's just please our prettier formatter on this markdown file please.
LGTM and a forced --check sounds good @ichard26 ๐
575220f Clarify check argument is needed for github act... - jlplenio
I'm not entirely sure about psf/black#3323, while it's a good idea in theory, Black doesn't have a grammar for each Python version and things can get confusing
I'll have to think about it for a little bit
https://ichard26.github.io/blog/2022/10/black-22.10.0/ is a thing now
Black 22.10.0 removes runtime support for Python 3.6, fixes a major fmt: off/on bug, and other QOL improvements.
Good way to truly understand what changed since honestly I haven't been following what's happening that closely lately. My GitHub inbox is a mess.
Oh! Please do raise it on the PR ๐๐ฟ
i trust you brother
Describe the bug
Black is overzealous about reformatting docstrings to a single line, and can cause the resulting line to be longer than the line length limit.
To Reproduce
For example, take this code:
def f():
"""89 123456789 123456789 123456789 123456789 123456789 123456789 123456789 12345678
"""
The first line of this docstring is exactly 88 characters. After blackening this code, this results in:
def f():
"""89 123456789 123456...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Description
Fix #3291 : incorrectly ignoring .gitignore presence when more than one source directory is specified. Commit message of the commit that fixed the bug:
When passing multiple src directories, the root gitignore was only applied to the first processed source. The reason is that, in the first source, exclude is None, but then the value gets overridden by re_compile_maybe_verbose(DEFAULT_EXCLUDES), so in the next iteration where the source is a directory, the conditi...
License
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Description
Fix #3315 : Fix incorrectly applied .gitignore rules by considering the .gitignore location and the relative path to the target file. Commit message of the commit that fixed the bug:
When a .gitignore file contains the special rule to ignore every subfolder content (*/*) and the file is located in a subfolder
relative to where the command is executed (root), the rule is incorrectly applied and ignores every file at the same level of the .gitignore file.
The...
does black have a policy about pep 257 in addition to pep 8?
we try to follow it but we have our own compatibility constraints now, and personally I'm not really persuaded by pure arguments from authority based on the PEP text
that's disappointing
the preview format violates pep257 but the stable form doesn't
and i think it looks much worse in the new form
do you mean the thing where we put the closing quotes on their own line? I agree we should change that
Description
Issue https://github.com/psf/black/issues/2097 raised the issue that is_type_comment only works for comments starting with # type:, and more spaces/tabs between # and type, or typeand : are valid as per typed-ast/ast, but not black.
This PR (for now!) only tries to make is_type_comment be consistent with typed-ast, not to remove the extra spaces/tabs if they are present.
I'd like some guidance as to:
- Using regex. Is there a way to perform this c...
Describe the bug
When running black using pre-commit against a generated Django migration file, the following error is observed:
โ backend git:(main) โ pre-commit run black --all-files
black....................................................................Failed
- hook id: black
- exit code: 123
error: cannot format backend/src/black_test.py: maximum recursion depth exceeded while calling a Python object
Oh no! ๐ฅ ๐ ๐ฅ
167 files left unchanged, 1 file fa...
I vaguely remember a pre-existing issue about this, hmmmmm
thats how all webhooks show up
yes, for single line docstrings
I opened an issue for it but was concerned when told may not be a bug https://github.com/psf/black/issues/3320
Is your feature request related to a problem? Please describe.
Sometimes I find myself needing small tables of data for configuration, for example a table containing units and upper and lower bounds for some pandas.DataFrame.
An example:
metadata = { # formatted with black
"Glucose": ["g/L", 0, 20],
"DOT": ["%", 0, 100],
"Volume": ["mL", 0, None],
}
I am deeply convinced that for this kind of manual data entries in source code, **fixed width ...
https://github.com/asottile/blacken-docs
I don't really know how to do this so I'll try and be succinct -- sorry this is off topic as well and that I deleted the issue template
for me, maintaining blacken-docs no longer sparks joy -- and it's not due to the integration with black (which has been fine since stable) -- but because docs are complicated (and, well, I don't actually use it).
I'd love to figure out a way forward where either this is adopted or integrated in some way...
Hmm, while my instinct is to help take on maintainership of the project, I barely can keep up with maintenance of Black so it's probable I can't reasonably pick up another project.
I have some thoughts about this, but I'll write them up later once I have some free time
Getting the error
<_io.TextIOWrapper name=4 encoding='cp1252'>
Description
Fixes a minor typo "iff" -> "if" in the comments docstring
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? (not necessary) - [ ] Add / update tests if necessary? (not necessary)
- [ ] Add new / update outdated documentation? (not necessary)
Describe the bug
When I run Black as a commit hook via pre-commit it ignores # fmt: skip on a long lines (mb somewhere else).
I afraid that it may ignore # fmt: skip pragmas totally, making Black unusable for me as a pre-commit tool.
To Reproduce
have a pre-commit with .pre-commit-config.yaml
# Pre-commit config, see: https://pre-commit.com/
repos:
- repo: https://github.com/psf/black
rev: '22.10.0'
hooks:
- id: black
install hooks ...
Black breaks long lines with multiple sets of parentheses at the first set of parentheses that is before the character limit, as far as I can tell. This is a problem when you have lines like this:
assert nx.number_of_selfloops(G) == len(arch_elements), f"Not all elements have self-loops:\n {set(arch_elements) - set(nx.selfloops(G))}"
Because black breaks them like this:
assert nx.number_of_selfloops(G) == len(
arch_elements
), f"Not a...
Description
Closes #2484
Closes #2382
Currently, empty and whitespace-only (with or without newlines) are not modified. In some discussions (issues and pull requests) consesus was to reformat whitespace-only files to empty or single-character files, preserving line endings when possible. With that said, this PR introduces the following behaviors:
- Empty files are left as is
- Whitespace-only files (no newline) reformat into empty files
- Whitespace-only files (1 or more newl...
No, tabs for indentation are the devil. Making this configurable would go against Black's philosophy.
_Originally posted by @ambv in https://github.com/psf/black/issues/47#issuecomment-374964663_
I'm brining up again. I found one fork that uses tab's but its getting old. I'm not going to try to reason why tabs are better (and believe me I have good reasons). I'm trying to make working fork right now but hitting hard with tests, I've modified the tests to include tabs instead ...
>black -c "(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)"
(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(
1,
)
>black -c "(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1)"
(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(
1,
)(1)
``` weird ๐
out of curiosity, why is a set used here instead of a tuple? aren't tuples more efficient?
# black/__init__.py
def _format_str_once(src_contents: str, *, mode: Mode) -> str:
# ...
empty_line = Line(mode=mode)
after = 0
split_line_features = {
feature
for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF} # <- Here
if supports_feature(versions, feature)
}
for current_line in lines.visit(src_node):
# ...
No explicit reason, whoever wrote that probably just preferred sets. The runtime difference is almost certainly negligible.
I wonder if this is hacktoberfest related. Folks running spellcheckers so they can file easy PRs.
Allright! Sorry I was just browsing trough the codebase and got curious about that. I was taking a look at https://github.com/psf/black/issues/3072, looks though but surely it's a fun one to debug
ah I see, I've been mostly inactive for the past few months so I don't really know what's going on in the repo.
that does seem like a fun one to debug, I'd guess an earlier bugfix led to this bug
I think I wrote that. I preferred sets because conceptually split_line_features is unordered, so sets seemed more semantically appropriate
oh ok, got it!
LGTM! Hopefully a maintainer will answer the questions on your PR description :)
Is your feature request related to a problem? Please describe.
As I've been working on some black issues and overall getting a hang of the repo, I got really frustrated when debugging methods which name an arg or a variable as the built-in type, for example
def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing
You can find many of these with pylint src --disable=all --enable=redefined-builtin
Describe the solution you'd like
There ...
What does everyone think about https://github.com/psf/black/issues/2188#issuecomment-1289317647?
I know there's probably been discussion, but I don't like we're introducing a regex to parse for broken syntactical usages of a deprecated (or are there valid uses I don't know of for type comments) feature of Python ...
IIRC that PR changed the empty line tracking logic substantially. That might kill my post-docstrings empty lines PR haha
How does this affect formatting in practice? It's not clear to me whether this will need to go in the preview style.
Also, you need a changelog entry.
I feel like this will create more user confusion:
% black --target-version py36 -c 'a++'
a++
error: cannot format : Cannot parse (python 3.0): 1:3: a++
% black --target-version py39 -c 'a++'
a++
error: cannot format : Cannot parse (python 3.7): 1:3: a++
Users are going to wonder why it says "3.0" or "3.7" when they never asked for that version.
Looking at the diff-shades output I'm still a bit nervous whether this is a net positive, since it does often feel like it's adding unnecessary lines. But I guess that's what we have a preview style for.
We're getting warnings like https://github.com/psf/black/actions/runs/3325521041/jobs/5498291478 and I'm not sure how to fix them. I'll open an issue for a long-term solution, but for now avoid 3.0.2 to unbreak CI.
pytest-xdist 3.0.2 was released today and broke our CI with a DeprecationWarning. On a quick look I couldn't figure out how to fix it (we don't use the rsyncdir option explicitly), so I pinned pytest-xdist to Traceback (most recent call last):
INTERNALERROR> File "/home/runner/work/black/black/.tox/311/lib/python3.11/site-packages/_pytest/main.py", line 266, in wrap_session
INTERNALERROR> config._do_configure()
INTERNALERROR> File "/home/runner/work/black/black/.tox/311/lib/pyth...
I'm sorry ๐
Ah don't worry about it, the chance of me getting to it anytime is about zero anyway ๐
Is your feature request related to a problem? Please describe.
PEP8 says that dunder names like __all__ shall be before import statements, but after the __future__ statement.
Describe the solution you'd like
How about to move the dunder names to their place according to PEP8 using the black?
Black doesn't seem to be able to handle the double .replace() line in
dump.writelines(
[
"Blabla\n",
raw_dump.stdout.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1).replace(f"Database: {schema}", f"Database: `{PLANT_CODE}_{schema}`", 1),
]
)
Do I just need to nudge it in the right direction or is this outside of Black's capabilities? The line is clearly too long.
Personally, I'd probably do something like this.
dump.writelines(
[
"Blabla\n",
raw_dump.stdout.replace(
"CREATE TABLE",
"CREATE TABLE IF NOT EXISTS",
1).replace(
f"Database: {schema}",
f"Database: `{PLANT_CODE}_{schema}`",
1
),
]
)
Or is this just a case of something Black shouldn't even begin to deal with because I should have done the replacements in previous lines to not have this mess in the first place?
https://black.vercel.app/ seems to do something quite sane
dump.writelines(
[
"Blabla\n",
raw_dump.stdout.replace(
"CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1
).replace(f"Database: {schema}", f"Database: `{PLANT_CODE}_{schema}`", 1),
]
)
what version of black are you running?
22.10.0
and it doesn't give the above output?
While playing around, I just found out that Black isn't actually doing anything at the moment in VS Code.
I think something is wrong with the integration
I just moved up a function definitions two lines and it didn't move it back. Which it was doing just recently.
Ah, #editors-ides might be able to help
Yeah, thought it was a Black problem initially but doesn't seem like it
Hello! :heart: :laughing: :rofl: :smile:
First :one: of all, thank you :bow: for an amazing tool. :lollipop: I use it all the time. :watch:
I wrote a tool :wrench: which cleans :soap: :bath: :shower: all(:question:) emojis :hankey: from Black's :black_flag: output:
pip install . installs an executable script named black. Whenever you run it, it will run the next-in-line executable named black in your which -a black, and filter both stdout and stderr through a regular expr...
is there a way to stop black from adding two empty lines after a function or class
is it bad?
in some place i have huge hierarchy of empty classes (dont ask me why)
class Base: ...
class A(Base): ...
class B(Base): ...
class C(B): ...
class D(A): ...
# etc...
i need to put #fmt: off around this code, otherwise every line becomes 4 lines (class def line, ... line, two empty lines)
please consider the following suggestion: if class body is empty (pass or ...), dont add empty lines after class and leave class body on same line
but it will auto insert them
Describe the bug
In the following code:
import math
# a most excellent class
class MyClass:
PI = math.pi
Black fails to add an extra newline before the comment. This causes flake8 to give an E302 error.
Black does add a newline if you delete the comment, so I think this is an issue with Black.
To Reproduce
Run this in Bash on a Linux/Unix system:
cat > foo.py <<EOF
import math
# a most excellent class
class MyClass:
PI = math.pi
EOF
...
Description
Thanks for this awesome tool, just add one more organization!
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
I wonder if we should change "Facebook" to "Meta" in that list ๐
Looks fine to me, felix approved, but I have very little vim plugin skill ... #blindMerge
4bb6e4f Vim plugin: allow using system black rather tha... - bugfood
Description
This fixes #3350.
The problem is that when Black encounters standalone comments on one line inside brackets, it splits the line using delimiter_split. This will split on the comment, but it will also split the line on the highest priority delimiter, which isn't always necessary.
I've added a comma_split function, which is the same as delimiter_split, but delimiter_priority = COMMA_PRIORITY. Black will now try comment_split before it tries delimiter_split. Th...
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
References #3355 3355
Say I'd like to format my code like so:
v = (
foo_dict
.setdefault("a", {})
.setdefault("b", {})
.setdefault("c", {})
.setdefault("d", {})
.setdefault("e", {})
)
Black will of course reformat this to put foo_dict.setdefault("a", {}) on the first line.
Luckily, there are [directives to not auto-format some lines](doesnโt reformat lines that end with # fmt: skip):
[black] doesnโt reformat lines that end with # fmt: skip
Yet this doesn't w...
Revert deleted documentation on setting up Black using IntelliJ external tool or file watcher utilities
Issue: https://github.com/psf/black/issues/3271
Description
Add documentation section on how to set up black in IntelliJ products using either File Watcher or External Tools utilities
Checklist
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
3179a44 Bump peter-evans/create-or-update-comment from ... - dependabot[bot]
f677914 Bump pypa/cibuildwheel from 2.10.2 to 2.11.2 (#... - dependabot[bot]
How do I locally compile the repository?
I want to use black with personal modifications (the community doesn't want it, for sure, saw discussions about it)
I forked black, I installed everything needed, and I can now pass all tests with "tox -e py".
how do I compile it? when I run "mypy src --config-file mypy.ini" it throws
error: Library stubs not installed for "typed_ast" (or incompatible with Python 3.7)
The venv is python 3.9.
pip freeze shows:
aiohttp==3.8.3
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
-e git+https://github.com/YuvalZilber/black.git@4bb6e4f64ab3820ab9fae6716cd59479d34b7edf#egg=black
cfgv==3.3.1
charset-normalizer==2.1.1
click==8.1.3
coverage==6.5.0
distlib==0.3.6
exceptiongroup==1.0.0
execnet==1.9.0
filelock==3.8.0
frozenlist==1.3.1
identify==2.5.8
idna==3.4
iniconfig==1.1.1
multidict==6.0.2
mypy-extensions==0.4.3
nodeenv==1.7.0
packaging==21.3
pathspec==0.10.1
platformdirs==2.5.2
pluggy==1.0.0
pre-commit==2.20.0
py==1.11.0
pyparsing==3.0.9
pytest==7.2.0
pytest-cov==4.0.0
pytest-forked==1.4.0
pytest-xdist==2.5.0
PyYAML==6.0
six==1.16.0
toml==0.10.2
tomli==2.0.1
tox==3.27.0
typing_extensions==4.4.0
virtualenv==20.16.6
yarl==1.8.1
try looking into CI, how it's compiled there
Hey could someone provide a sample to test black with different target-versions? I'm not quite clear how it's meant to work, and I'd like to test if my configuration is picked up correctly
Ah, I've managed to find the list of feature: version, I think I can figure it out from here
Description
When an assignment statement's left hand side fits on a single line, prefer splitting the right hand side's outer optional parens.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Description
Just thought adding this to the docs so I don't need to remember this anymore.
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ x ] Add new / update outdated documentation?
Is there a convenient way to run locally whatever diff-shades runs on the CI?
Description
Correctly handle trailing commas that are inside a line's leading non-nested parens.
- Fixes #1671
- Fixes #3229
This also improves the formatting on #2052, though it still results in unnecessary line breaks:
# Unformatted:
x = {
"string": str,
"integer": int,
}[key](value)
# Before the fix:
x = {"string": str, "integer": int,}[
key
](value)
# After the fix:
x = {
"string": str,
"integer": int,
}[
key
]...
TIL: black is formatting #fmt:off and #fmt:on comments
I don't think it's easy, but you should be able to find the commands somewhere in .github/workflows/ and run them yourself
Thanks, that was my guess. I was wondering if anyone already has a wrapper/script that I can reuse.
https://github.com/psf/black/actions/runs/3371600936/jobs/5594046616#step:9:103
I'm confused why this can raise a KeyError in diff-shades? I can't reproduce it locally running diff-shades analyze. (I should switch to from enum import Enum, auto but I'm still puzzled by the error)
IIRC this is a mypyc bug, it doesn't compile enum.Enum correctly
One does not exist right now, would you find one helpful?
there ya go
Yes that would be helpful. I'm working on two PRs where I need diff-shades to find out all the corner cases. But using a draft PR with the CI also work
The workflow used to support workflow_dispatch so you could call it manually (on any revisions) but I got rid of it because no one used it
A local wrapper would be good, I agree
workflow_dispatch still runs the CI not locally right?
yeah
The best way of running diff-shades like CI locally would be to...
- Download the latest preview-changes analysis for main from the PR (or a recent one if the current PR does not have a passing run yet) -- you can download
preview-changes-main-f67791427d.jsonfrom https://github.com/psf/black/actions/runs/3365491825 - Install diff-shades locally
python -m pip install https://github.com/ichard26/diff-shades/archive/main.zip - Install your local copy of Black in the same environment you installed diff-shades
- Run
diff-shades analyze your-copy.json --work-dir projects-cache/ --repeat-projects-from downloaded-main-analysis.json - Run
diff-shades compare downloaded-main-analysis.json your-copy.json --diff(probably want to redirect to a file)
More docs here: https://github.com/ichard26/diff-shades#installation
oh thanks! I didn't realize the trick to download the results from an existing run for comparison
Yeah, you could gather your baseline data for main yourself, but downloading it from a pre-existing run is faster :)
I understand this is a little confusing if you aren't the one who wrote diff-shades :)
Actually, you can replace all of the file extensions with .zip, diff-shades has built-in support for zipped analyses
Describe the bug
Black does not break lines containing class member access even though character line limit is exceeded.
To Reproduce
Given this code using dataclasses with long member names:
from dataclasses import dataclass
@dataclass
class SomeNestedDataclass:
very_long_nested_dataclass_variable_name: str
@dataclass
class SomeDataclass:
long_dataclass_variable_name: SomeNestedDataclass
def some_func(some_datclass_param):
pass
...
Describe the bug
To Reproduce
Run black on this code, and observe a change that should not have happened.
def recv(
self,
) -> (
# fmt: off
gym_old_venv_step_type # old API step
| gym_new_venv_step_type # new API step
| tuple[np.ndarray, dict] # new API reset
| np.ndarray # old API reset
): # fmt: on # noqa:E125
...
Reformatting happens on the line before # fmt: on, with comment moved...
Is there a way to tune my black notifications to not tell me about draft PRs that I missed?
I'm sorry if this is from my two recent PRs, I initially created them as regular PRs then converted them to drafts ๐
Though I'm not sure pushing new commits to draft PRs will or will not create notifications?
Yup. I get em ๐
I didn't realize that, I'll keep that in mind.
you can disable it by using --skip-string-normalization/-S flag
Hi everybody, I have a peculiar error when trying to use black.
$ black
Traceback (most recent call last):
File "/home/ale/miniconda3/envs/sfhfinder/bin/black", line 7, in <module>
from black import patched_main
File "src/black/__init__.py", line 41, in <module>
File "src/black/nodes.py", line 37, in <module>
File "src/blib2to3/pygram.py", line 186, in initialize
File "src/blib2to3/pygram.py", line 32, in __init__
AttributeError: '_python_symbols' object has no attribute 'tname_star'
I do not know how to solve it, but I do not want to open an issue immediately.
I'm using Python 3.10.6 and Black 22.3.0.
you probably have some strange half-compiled installation (note the src/ path)
I guess I should delete and re-create the environment then?
Is your feature request related to a problem? Please describe.
I'm used to run black --check --diff --color to see format suggestions by Black and apply them myself. I do this because I intend to improve my coding skills by reading and writing better code, and also because sometimes renaming a variable, using a better indentation or placing a comma properly is a task that a human can do better than Black (sometimes). I've recently faced some problems when the output of the diff is t...
This is most apparent when black is run via pre-commit which does
subprocess.Popen(stdout=PIPE).
One option around this would be to instruct users to set PYTHONUTF8=1,
but that is not a very good approach, as basically everything supports
UTF-8 these days.
This fix was inspired by pycln and https://github.com/hadialqattan/pycln/issues/54
Fixes #3156
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary?
Thanks for your contribution!
Monkeypatching sys.stdout feels quite risky though. A few questions:
- What will happen on Windows terminals that use an encoding incompatible with UTF-8? I'm worried we'll get mojibake in that case.
- Could this be fixed in
clickinstead? We useclick.echoto output all emoji, andclickis supposed to take care of output encoding for us. - The
pyclnissue reported gettingUnicodeEncodeError, while the OP of the Black issue saw literal\u1234...
just for transparency, we briefly talked about it before
I definitely did some testing back then which worked but I think I ran into some wall with a case where it doesn't quite work and just dropped it. No idea what the case was so there's that lol
Is this related to a problem? Please describe.
This is a suggestion to improve some ambiguity in the Pragmatism section of the documentation.
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#ast-before-and-after-formatting
Current text (first paragraph of section 'AST before and after formatting')
When run with --safe, Black checks that the code before and after is semantically equivalent. This check is done by comparing the AST of the source with t...
Hey I just wanted to say thanks for the PR. I really appreciate it! Also thank you @JelleZijlstra for the review! ๐งก
The PR overall looked good, but two things stood out to me on a quick scan.
I was genuinely confused hearing the Discord notification sound for this. It didn't register this was caused by my review ๐
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
how's black's mypyc stuff doing these days? i know for a bit there was some stuff blocking you from using latest mypy... is that all resolved?
we're on 0.971 at the moment, I don't recall what if any the blocker is for 0.982
There isn't any, other than me testing it out and then bumping mypy in pyproject.toml
is the test procedure documented?
Nope, I typically just bump mypy in my personal black-mypyc-wheels repository and fire a test build and verify it passes
I should really document and make myself not the SPOF for all things mypyc related....
I was going to suggest you put something in https://black.readthedocs.io/en/stable/contributing/release_process.html or a related page and give me/Cooper/some other people access to your wheels repo ๐
I'll add that to my to-do list for Black
actually it's already on there since August 3 ๐ฅด
does black supports plugins?
for example, plugin can preprocess source code so black can understand it, then black formats it, and then plugin preprocesses code back
no
yes, that's possible
we don't formally have an API but you can also import black and call black.format_str
it's quite convenient, thanks
any chance could https://github.com/psf/black/pull/3370 be reviewed soon? ๐
Description
Correctly handle trailing commas that are inside a line's leading non-nested parens.
Fixes #1671
Fixes #3229
Checklist - did you ...
Add an entry in CHANGES.md if necessary?
...
the diff-shades diff in https://github.com/psf/black/actions/runs/3375631261/jobs/5602457956#step:10:1 is pretty ugly but it's what people are asking for if they put the trailing comma ๐
if you look at the first example, the original code was written in that way with line exploded ๐ https://github.com/django/django/commit/1ca825e4dc186da2b93292b5c848a3e5445968d7
then Black merged it later
Description
Fix for issue #3268.
As per the Black spec
The magic trailing comma
...
However, there are cases where you put a short collection or function call in your code but you anticipate it will grow in the future.
...
Now, you can communicate that you donโt want that by putting a trailing comma in the collection yourself. When you do, Black will know to *...
fixes #3375
Description
The docs had ambiguity about the --safe flag as pointed out in #3375. This PR improves the clarity of the docs.
Checklist - did you ...
- [X] Add an entry in
CHANGES.mdif necessary? - [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
I don't think this needs to be noted in CHANGES.md. Of course, I can if it is desired.
Shoot, of course upon merge I realized this is targetting the stable branch.
just saw that too in the email
I'll fix that, but man what a terrible start to the morning.
might have to force push it out?
Yeah, I'll do git switch stable && git reset HEAD~1 && git push --force
So this is the one actual downside of stable being a branch. We fix RTD but we get these PRs ๐
I wonder if GH has a config to disallow PRs by branch
I was wondering the same thing
You can lock a branch, but that makes it read-only to everyone (even GHA I'd imagine), hmm.
yeah that's what it looks like
oh wait do we have automation now to update the branch? pretty sure I can make it so only GHA can push to it
Yup, but how? Reading the docs doesn't show any option to do that...
Neither do I
https://github.com/community/community/discussions/13836 sounds like it's impossible.
I guess the best option to add a simple step to the lint workflow that fails if the target branch is wrong
I'll make an issue
TIL you can do git cherry-pick stable, very nice.
#3378 was just accidentally merged into the stable branch, which should only be updated after releases. There appears to be no way to use branch protection rules to disallow such PRs (community/community#13836). To prevent similar mistakes in the future, we should have some check on PRs that fails if the target isn't main.
a branch is just a pointer to a commit so you can cherry-pick it ๐
Anyway I feel like an idiot.
don't worry about it! it's very easy to miss
I think this is my first time pushing to main directly haha
if you hadn't done it I'd have merged that PR and made the same mistake
OK moved the commit from stable to main.
Yea, this isn't our first time though haha. I wonder if I merged the previous PR that did this.
Thanks for opening the issue!
It's way too easy to miss it, sounds like GitHub should make it more obvious when the PR isn't targeting the default branch.
FWIW, I'm going to try to at least catch up on the recent PR activity today, so if there's any PRs ready to be merged, I'd appreciate waiting.
Really? I never thought about branches as commits. I thought that every branch is like a some set of commits.
the branch points to the commit at the tip, and every commit has one or more parents
Yeah, nice and convenient idea
has anyone seen setuptools-scm produce a version file with completely zeroed out content? or alternatively cibuildwheel producing a wheel where a file is zeroed out?
Nope, how odd.
Looks fine in general, I don't like how poorly the tests read, but that's more a symptom of the poor test setup and infrastructure (ie. it's not your fault).
Almost there! The problem where Black blows up with invalid python-requires is still there.
--verbose still doesn't say what target version were inferred, but I'm happy to defer this as a future improvement since the per-file autodetection isn't logged anywhere either. A quick note about the changelog otherwise.
Thank you so much for your patience again!
I feel bad reviewing so late.
I got through a little bit of the backlog, but I still have a ton of stuff to catch up on. Looks like I'll have to do this piece by piece day by day since I don't much free time these days.
The problem is that proper PR reviews take tens of minutes if not hours and I'm not willing to sacrifice that since quality is important.
Oh wow, upgrading mypy to 0.990 doesn't net any new type errors.
The code is solid (and thanks for persisting with this PR!) but as before I am not happy with the new lines inserted into multiline docstrings. The change is disruptive enough in Black itself that the PR becomes hard to read.
Thanks for writing this up and putting it under the preview style.
I'm not yet convinced we should do this, since it could be disruptive. diff-shades currently gives us results only for pyanalyze (which happens to be my code), because it runs black with preview = True. As you see, I currently use a different docstring style :)
I'd be curious to see the result on more open-source code. Could you push a change to enable the new style without preview mode, so that we can see the diff-sha...
How would i format on save using black? (I use nvim btw)
you need plugin for nvim
I think you can use the vim plugin, that black offers, with neovim as well
Description
Fixes GH-3376.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary? -> n/a
- [x] Add new / update outdated documentation? -> n/a
diff-shades preview-changes is getting concerningly slow. I should probably start looking into implementing sharding.
Or alternatively split the baseline and target revisions across multiple jobs
@chrome plover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
black, 22.10.0 (compiled: yes)
Python (CPython) 3.10.2
After applying Black:
def f2(some_name1, some_name2):
if (some_name1.is_constant or some_name1.is_affine) and (
some_name2.is_constant or some_name2.is_affine
):
pass
def f3(some_name1, some_name2):
if (
(some_name1.is_constant or some_name1.is_affine)
and (some_name2.is_constant or some_name2.is_affine)
and (some_name3.is_constant or some_name3.i...
I'm alright with making the default Black version tied to the action version being used. For context
versionwas introduced because the action didn't exist for a long time so tying black version to action version wouldn't work for version 19.10b0 for example. In hidesight, having the default being the action version keeping theversionconfiguration option around as an escape hatch is the better solution. This will involve some complexity since commit SHAs aren't supported by the versio...
Description
Minor tweak to the language in the description of the current style.
In a nutshell, I think the original author meant to say "real-world" rather than "realtime."
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? -> not necessary - [x] Add / update tests if necessary? -> not necessary
- [x] Add new / update outdated documentation?
My understanding is that this PR should get the magical label to silence the CHANGELOG entry check.
Many thanks. Yup, this makes more sense.
If CI passes I'll merge.
Describe the bug
When trying to format a project from the outside, the verbose output shows says that there are symbolic links that points outside of the project, but displays the wrong project path. This behavior seem to be triggered when the command is executed from outside a project on a folder.
To Reproduce
Consider the following tree:
.
โโโ home/
โโโ project/
โโโ .git
โโโ dir/
โโโ main.py
When trying to format a fol...
Description
Closes #3384
When trying to format a project from the outside, the verbose output shows says that there are symbolic links that points outside of the project, but displays the wrong project path. This behavior seem to be triggered when the command is executed from outside a project on a folder, causing an inconsistency between the path to the detected project root and the relative path to the target contents. The fix is to normalize the target path using the project roo...
Is your feature request related to a problem? Please describe.
Sometimes when dealing with multiple environment settings, IDEs, and pyproject.toml files etc. etc. is beneficial for a project team to have a confirmation about the actual applied black-settings ("line length") in the CI CD pipeline.
black -v will show a line like this: Using configuration from project root..
However, it doesn't tell us what the settings are, and it is not desirable to have all the other output of...
Is there a performance concern when the Preview formatting moves to stable in a new year cycle?
we should make sure everything we put into stable is performant. IIRC part of the reason we didn't move experimental string processing to stable before is that it has quadratic performance in some edge cases, I'll have to check if that's still an issue
relatedly, 2023 is approaching, so we should make decisions on what parts of the preview style to move into stable
I think in early December I'll make an issue to discuss all the preview changes and decide whether any should be reversed or left in preview for now
This is all great, thanks!
Hi. I'm the person behind this pull request https://github.com/psf/black/pull/3377. So I think that the behavior I changed is a bug fix in that the previous behavior caused formatting bugs by both yielding early and not yielding still-omittable sibling-level trailers after exiting prematurely due to finding magic commas.
The regression in trailing_comma_optional_parens2 is due to a slight change in the parse tree: picking the first tuple instead of the second one as the place to insert the magic commas. This is probably because the length escape for generate_trailers_to_omit also will yield omittable trailers, but is somewhat inconsistent the existing behavior of the function. The change I applied minimizes the number of regressions, but it also defeats the point of using the generator. At this point, I'm unsure of where to go next or if this will require more of a rewrite.
Looking at the differences in the assert-no-changes CI job, some previously bad lines such the one below are fixed, but there are several breakages where the RHS is kept together tighter than the rest when as per https://github.com/psf/black/pull/3368, the RHS should be split first.
--- a/django:tests/queries/tests.py
+++ b/django:tests/queries/tests.py
@@ -3320,13 +3320,13 @@
) | JobResponsibilities.objects.exclude(
job__responsibilities__description="foo",
)
self.assertCountEqual(
Job.objects.annotate(
- responsibility=subquery.filter(job=OuterRef("name"),).values(
- "id"
- )[:1]
+ responsibility=subquery.filter(
+ job=OuterRef("name"),
+ ).values("id")[:1]
The long-line problem where long lines will all of the trailers at once instead of incrementally is also showing.
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Been using black for quite some time, great job on it. One question I would have for easier navigation, perhaps, are there any thoughts of including the following when passing the --diff flag:
1. have the + and - signs be colored for better visibility
2. enumerate the affected lines with their respective line numbers
I think these would be quite a nice qol changes on a daily. Thank you
Fixes #3072
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Is your feature request related to a problem? Please describe.
If a user wants to require a certain aspect in pyproject.toml, he can do it. If he doesn't do it, then it means he doesn't care. It should be up to the global config of the one running the tool. If a user wants to enforce the black-default value, he can define a field, but leave it as None and black should set the default value for that field.
Describe the solution you'd like
config = dict(globalC...
Resolving #3386
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Fixing #3072
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Looks like https://github.com/psf/black/pull/3254#issuecomment-1236197864 went stale, so here's a PR to fix the installation instructions and make them cross-shell
is this the expected behavior?
encoding = tokenizer(text, return_tensors=FRAMEWORK, truncation=True,).to(
device
) #
vs
encoding = tokenizer(
text,
return_tensors=FRAMEWORK,
truncation=True,
).to(device)
the # negates the trailing coma
pip freeze | grep black
black==22.10.0
It's related to https://github.com/psf/black/issues/3268
I started on a fix, but it causes some regressions and I'm not sure how to move on
Sorry for taking so long to get back to you. 1 already exists, you just need to pass the --color flag (perhaps we should make it the default?). 2 could be useful (although line ranges are available in the chunk headers) but would make the output unapplicable (eg. git apply or VSC's legacy Black integration) ... so we'd have to add another flag.
Thank you!
You're welcome to open an issue to make --color the default FWIW.
Im down for color default. It might make some logs messy if we donโt detect non terminals correctly but we use a mature library for color right? (Canโt remember what we use)
And, should that go into preview? LoL
As in, itโs not changed till 23.1.0
seems like the --color flag only affects diffs for what it's worth. I feel like a lot of --diff users probably use the output programmatically somehow, in which case color may be bad
And we don't need to wait for 23.1.0 to change this, since it doesn't affect formatting
Is your feature request related to a problem? Please describe.
I'm trying to integrate black into a bazel project, run as a bazel test, to check python formatting at precommit. For sandboxing reasons, bazel tests don't run on the source files directly, but on a special output directory with symlinks to the source files. However, black skips symlinks, so it skips all the files and reports success, without actually having checked any of the files.
Describe the solution you'd like
...
what is black formatter?
An autoformatter for Python code, have you tried https://black.vercel.app/ yet? It's a neat demo
Playground for Black, the uncompromising Python code formatter.
is there #fmt:off, but only for one line?
# fmt: off
x=[1,2,3,4,5]
# fmt: on
# VS
x=[1,2,3,4,5] # fmt: off-one-line
# fmt: skip
Anyone know what a black formatter is ?
You already got the answer here
Thanks
Hey there!
I just noticed that under the following configuration:
- Ubuntu 20.04 with the following kernel:
Linux ubuntu 5.15.0-53-generic #59~20.04.1-Ubuntu SMP Thu Oct 20 15:10:22 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux - Using python 3.10 installed via apt from the
ppa:deadsnakes/pparepository:Python 3.10.8 (main, Oct 12 2022, 19:14:26) [GCC 9.4.0] on linuxpip 22.3.1 from ~/black_test/lib/python3.10/site-packages/pip (python 3.10)
Installing black on ver...
84105992682cfadf3cfbd9ccdaf9246b72e05b2f59e4a751d5398ad6e983ee6f
I would love to have Leo use Black as Leo's one-and-only code formatter. That's not possible at present.
The problem
Leo uses sentinels, comments starting with #@ (no space after the pound sign), to denote outline structure. Sentinels appear in the external files that Leo produces.
This convention goes back more than two decades. Recent versions of Leo can read external files with black-formatted sentinels, but writing black-formatted sentin...
Is this related to a problem? Please describe.
https://discord.com/invite/RtVdv86PrH is not a valid invite


Describe the solution you'd like
Fixing the broken link :)
hm when I click that link it takes me to the home page for this server
I think it's supposed to be directly for this channel though?
i think they might just be banned
weird, that user has been a very helpful contributor to typeshed
although i cant find anything from them here
Describe the style change
When validating a project with both pyright and mypy, it's possible to independently validate both checkers.
However, both expect their ignore comment to be at the start of the line.
Examples in the current Black style
line-lenght=130
class Task(Future[_T_co], Generic[_T_co]): # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues]
# [...]
pass
Desired style
class Task( # type: i...
fyi-- https://github.com/psf/black/pull/3368 is ready for review, in case anyone has a few cycles this week ๐
Discord web cache issue. No worries, I got it figured out!
Description
I wanted to start taking good care of quality of code in my project. In order to achieve this, obviously I had to implement black. When black corrected all my formatting mistakes and then I run it again (just in case) I saw following message (TRIGGER WARNING):
All done! โจ ๐ฐ โจ
And I was schocked. I did not even realise how hungry I was, and the cake looked to delicious. I should add that I'm trying to loose weight. This delightful piece of confectionery art wok...
Is this related to a problem? Please describe.
You like to call yourself "PEP 8 compliant", but at the same time you are definitely not:
- line length:
- #497
- #498
- #855
- #1252
- #1512
- function's closing brackets:
- #1178
Describe the solution you'd like
Now, unlike most people, I do not want you to change the style. I find the formatting quit...
So I love named (keyword) arguments, I use them even when they're not required, I think it improves code readability.
def randint(min, max):
return random.randint(min, max)
randint(
min = 0,
max = 2**256 - 1
)
The issue is black removes the whitespace around =, which hinders readability.
In the ideal world, black would offer several options:
remove whitespace for named arguments(current)num spaces for named arguments(specify a numbe...
hello
i don't think this is a huge deal personally
"A Foolish Consistency is the Hobgoblin of Little Minds" and all that
black rationalizes all of its decisions, and thus complies with pep 8 in that regard
but i guess others view that differently ยฏ_(ใ)_/ยฏ
(if it were up to me iโd just not mention pep 8. itโll shut people up. pep 8 was never meant to be a style guide for all of python. blackโs style isnโt going to change regardless)
WHAT IS BLACK DOING AGAINST PEP 8?
ah, four of those issues linked are about the line length
Uh, first time I see this, but apparently black is trying to reformat code in a way that violates PEP-8?
Line in question, after reformatted by black:
compart1, compart2 = rucksack[: len(rucksack) // 2], rucksack[len(rucksack) // 2 :]
A nice, thanks!
Alright, I changed the reformat tool used in pycharm to black, but now it suddenly ignores the configs I set for it in pyproject.toml. Can I have the integration with the IDE read these configs somehow?
Seems like a few are present in the formatting options menu of blackconnect, they will be sufficient for now
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
would reformat cogs/autobuy.py
would reformat cogs/commands.py
would reformat cogs/hl.py
would reformat cogs/blackjack.py
would reformat cogs/pm.py
would reformat cogs/search.py
cogs/stream.py already well formatted, good job.
would reformat cogs/trivia.py
would reformat cogs/minigames.py
resources/icons.py already well formatted, good job.
would reformat main.py
resources/interface.py already well formatted, good job.
Oh no! ๐ฅ ๐ ๐ฅ
9 files would be reformatted, 3 files would be left unchanged.
Error: Process completed with exit code 1.```
How can i make the black github action reformat instead of showing an error?
action.yml line 5
options:```
I installed black formatter, and I can use it inside Visual Code by using the standard keybind: ALT + SHIFT + F
however within the terminal I wish to use a command to execute black. I am using pipenv and I cant get it to work. Let me show you
Nvm i solved it by doing:
PS C:\Users\...\pdf_creator> pipenv run black "../pdf_creator"
All done! โจ ๐ฐ โจ
9 files left unchanged.
yeah, black is installed as script in your environment, so you don't need to invoke it withpython ... prefix (just for some "why it works")
Thanks to mypyc, black runs twice as fast when installed by PyPI vs in a pre-commit hook https://github.com/pandas-dev/pandas/pull/49947
Would you be open to making a mirror repo, like this one that exists for ruff, which will install black wheels and thus be fast?
Hmm just curious, at type hints, what is the logic behind removing spaces at dict[int:str] but creating them at dict[int : list[str]]?
thats not a valid type hint fwiw
but its probably cause list[str] is considered a complex expression iirc?
Which of the two is not a valid type hint?
It seems like you are correct, , is used and not :. Thank you
I have a custom dialect of Python and I'd like to add black support for some of the specific constructs. Is there an "approved" way of doing this or will I end up needing to fork and hack?
you'll need to fork
you can write wrapper around black
- change your code to be valid python
- run black on it
- change code back
Interesting suggestion, I'll take a look and see if that's feasible/easier than forking. Thanks! Also thanks @dense jungle!
(VS Code)too much linting errors made by flake8, black formatter, how should I change the parameter?
If it thinks it's too long, I expect it should help me to split it into 2 lines, isn't it?
black's default line length is 88, not 79
Hello guys!
I start using flake8+black formatter today.
The code works, but the color of the code start going wrong in line 110
It's random color now.
Is that possible a bug from black formatter? Thank you!
Describe the style change
In most cases, when the indentation level decreases, whether it is only one level or many, the previous logical block is ended.
This is true for all cases except when the line immediately after is either an else or an elif or an except.
The proposal is to enforce that a newline (or two for module level) always exists before that indentation level decrease.
This newline works as a visual clue to help the code reader understand which code blocks are l...
The first 2023 release is coming up, which means we'll have to decide which parts of the current preview style should go into the 2023 stable style, per our stability policy.
Here's how I propose we go about it:
- In this issue, I'll list all style changes in the current preview style
- We'll default to promoting every part of the preview style to the stable style.
- Anyone can comment here if they have concerns about a particular part of the new stable style. However, if the discussion...
fun fact I discovered I can edit release notes for old releases
yeah I think I fixed a typo doing that a while back
also it's dec. 8 already ๐
yes I realized today I promised weeks ago to create the issue above ^
here is mypy in preview style https://github.com/python/mypy/commit/0f15b8a2fbdd1f5a88f3a681a8b7dfc07ff90c01
I'll try to take a look this weekend
huh why does it remove parens here https://github.com/python/mypy/commit/0f15b8a2fbdd1f5a88f3a681a8b7dfc07ff90c01#diff-a7d2c40f4be6322cee498432ca9dbbc3a356c3cbcb61029231452f6638bb11b5, I thought we always added parens now
this looks weird https://github.com/python/mypy/commit/0f15b8a2fbdd1f5a88f3a681a8b7dfc07ff90c01#diff-80ac0f76c35467fef7c1d0dbf21f8ffa464bdcc1272a8ac87da70c1228cad9ea (will open some issues when I'm done)
some of the changes in teststubtest.py are a downgrade (i think i filed a similar-ish issue before though)
% cat eatcomment.py
if False:
with xxxxxxxxxx(
"mypy", # mypy-c doesn't support __package__
"py.typed", # a marker file for type information, we assume typeshed to live in the same dir
) as xxxxx:
pass
% black --diff --preview eatcomment.py
--- eatcomment.py 2022-12-09 02:39:37.001919 +0000
+++ eatcomment.py 2022-12-09 02:40:57.322777 +0000
@@ -1,6 +1,3 @@
if False:
- with xxxxxxxxxx(
- "mypy", # mypy-c doesn't support __package...
seems like we didn't release the change for this yet
hmm okay, i think https://github.com/python/mypy/commit/0f15b8a2fbdd1f5a88f3a681a8b7dfc07ff90c01#diff-64c76dab759f5e184794b869cd69f8a5afa97380e693e98b980025d5487dcfc1R1621-R1624 isn't quite the same thing as the issue i filed and i find the old one more readable
that one also goes well over the line length limit, want to open a new issue?
mypy uses line length 100, i think it's under the length limit
no it's 140
oh sorry yes obviously i got confused
Describe the bug
class X:
def f(self):
assert remove_color_code(output) == (
"error: not checking stubs due to mypy build errors:\n{}.pyi:2: "
'error: Name "f" already defined'.format(TEST_MODULE_NAME)
)
becomes
class X:
def f(self):
assert remove_color_code(
output
) == 'error: not checking stubs due to mypy build errors:\n{}.pyi:2: error: Name "f" already defined'.format(
...
thanks, added to the list of blockers in #3407. I don't think we should add anything to stable style that makes us go over the line length limit
and also agree the new formatting is ugly
"For 4. We should fix ..." <--- i think this is "for 5"
right, thanks
% cat quash.py
class X:
def generate_shared_lib_init(self) -> None:
emitter.emit_lines(
"{",
(
'static PyModuleDef def = {{ PyModuleDef_HEAD_INIT, "{}", NULL, -1, NULL, NULL }};'.format(
shared_lib_name(self.group_name)
)
),
)
% black --preview --diff quash.py
--- quash.py 2022-12-09 03:02:23.973269 +0000
+++ quash.py 2022-12-09 03:03:57.327044 +0000
@@ -1,10 +1,7 @@...
Workaround for #3312
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
@bright glacier if you have a few minutes
I believe only the x86-64 wheels were tagged correctly?
I'd have to check the logs, I can in 10 minutes
I think we uploaded wheels labeled as x86_64 that were actually arm64
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Ahhh yes - We should disable this. Forgot we had all optional enabled here.
Thanks!
Right, but that's why psf/black#3312 was filed in the first place. Since all of the jobs are producing wheels labelled for x86-64, only the x86-64 job produces usable wheels that should be uploaded.
Sorry for taking so long to get back to you, totally forgot.
oh right, the amd64 job uploaded its wheels but labeled them as x86_64
and it was able to do that because it was the first to finish
I feel like this is something delocate (auditwheel for macOS) should check for, but I don't even know who maintains that.
changed the PR to run only x86_64 instead
seems like an issue already exists? matthew-brett/delocate#132
9ace064 Bump peter-evans/find-comment from 2.0.1 to 2.1... - dependabot[bot]
Seems fine. I hope nothing broke since the last release, but nothing much has changed so all should be okay.
Thanks!
thanks for the review!
it's the least I can do, but you're welcome
ugh tests failed on pypy, I'm going to ignore that because this PR definitely isn't breaking pypy
hm the macos x86_64 job is also failing, I think because for testing it's installing the x86_64 wheels on an aarch64 system https://github.com/psf/black/actions/runs/3658832698/jobs/6184104544
guess we'll have no macos wheels today
linux wheels are here though, and the windows wheels are on their way
windows is done too