#black-formatter
1 messages ยท Page 34 of 1
it's a webhook
although, joe might be doing some filtering
Legend. Thanks
with cloudlfare workers
(https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks article by discord which uses github as an example)
I don't know whether cibuildwheel can produce a pure python wheel
I don't want it to and don't get why it is
usually you would do the sdist and pure wheel outside of cibuildwheel
I've seen some discussion about sdists in the issue tracker, but I don't know what that meant
Oh, you meant that cibuildwheel was building a pure python wheel locally
Yes
uhhhhh, probably something to do with the envvars, but I have never ran cibuildwheel locally
My goal was to try and get a local way to test it to learn
So I thought try move as much as I could to the pyproject.toml since that's supported now
How did you test it all, trial and error with the aciton?
yup.
I got the docker image and it was building in there, but for some reason was trying to build a native wheel
the only thing that comes to mind is that configuration is faulty since the BLACK_USE_MYPYC environment variable should've been set in the docker container
I would love to try it myself, but I'm busy today
That's cool - I might play again later
Giving bandersnatch it's once a year overhaul / love today
I want to update pypi's install but I can never get movement / agreement there ... They still on 4.4.0
and old requests + deps with bugs ๐
Hi folks!
Is there any Pycharm/IntelliJ plugins for black?
I'm find out well plugin like scalafmt on intellij.
In official docs, recommend use external tools
There's an integration with pycharm, and it's written in the docs, have you tried / seen that?
Yeah, I'm tried and apply it on my Pycharm. But I find out more something like as native plugin just install from market place.
Much better, and a nice simplification! Again, provided that other maintainers also agree with the style, and that the implementation itself is sound.
Restrict the GitHub token permissions only to the required ones; this way, even if the attackers will succeed in compromising your workflow, they wonโt be able to do much.
- Included permissions for the action. https://github.com/ossf/scorecard/blob/main/docs/checks.md#token-permissions
https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs
[Keeping your GitHub Actions a...
re: this, might be worth changing the workflow default in repository settings to read-only once this is merged so that by default the token has the minimum permissions
good idea, done
wasn't entirely sure if you had access to repository settings, guess you do then ๐
I have great powers
and great responsibilities
And the right person for the job
what exactly is this?
Description
Fixing this issue https://github.com/psf/black/issues/1632 where some docstrings were reformatted to be too long
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? Done
- [ ] Add / update tests if necessary?
I'm sure the example from the issue would make a good test but I'm not sure where to put it - [x] Add new / update outdated documentation? Don't think this is necessary
Black? I'd suggest going an reading the documentation linked in the channel topic. https://black.readthedocs.io/en/stable/
Interesting - As this is fixing a bug/regression - Does this go under --preview or not?
Anything in 22.1.0 that doesn't crash or eat comments or anything similarly terrible goes in the stable style. This should be preview only.
Ok, thanks. Was being lazy and didn't want to go re-read the policy
This action runs GitHub's industry-leading semantic code analysis engine, CodeQL, against a repository's source code to find security vulnerabilities.
https://github.com/ossf/scorecard/blob/main/docs/checks.md#sast
I haven't checked, but lets make sure development docs state about preview style + link to it - I'll try get to it today
Still some comments, hang in there! And thanks for your patience ๐
Hi! Thanks for the PR. I like the idea, since it's easier to just put a file in a folder rather than having to edit a list somewhere else. We could definitely do this for all the test categories. I'd be okay with doing it in a future PR, but thought I'd mention it already.
The changes themselves look alright to me. And to the best of my abilities I tried to verify that the correct files were indeed moved ๐ Nicely done!
!cban 550341177585434635 racism
:incoming_envelope: :ok_hand: applied ban to @broken stratus permanently.
!cban 550341177585434635 racism
hah
You are speed incarnate
This is a slight perf win for use-cases that don't invoke reformat_many(), but more importantly to me today it means I can use Black in pyscript or pyodide - i.e. client-side in the browser.
I admit that I wouldn't use it for https://black.vercel.app/ - the heavier initial load is probably worse than some server round-trips - but it's indispensable for demos like https://zhd.dev/ghostwriter/ which allow the user to run arbitrary code. In fact, that demo is using a custom wheel from ...
I like it! Let's make sure it doesn't break mypyc or anything though.
The comments are a nice touch ๐ I think I've convinced myself that this is working now, so LGTM! ๐
Yep, this looks fine! And thanks for considering taking on the whole task ๐
<!--
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 `...
As a member of @hbrunn's team, I just tested this script on some of our open PR branches and it works really well.
@hbrunn please check the linting of the script itself, and it looks like you'll want to add that changelog entry indeed.
Would this kind of API for read_data be more developer-friendly?
source, expected = read_data("simple_cases/expression.py")
vs what is currently proposed ...
source, expected = read_data("expression.py", cases_dir="simple_cases")
Anyway, this PR looks great to me regardless.
Just want to share my thanks, I am a HUGE fan of removing static manual lists like this!
#techdebtCleanup
'Tis not the channel for it mate, try the dedicated helps!
Where? If you dont mind me asking?
Sorry
Also just posting an exercise without showing what you've done to solve it yourself could be considered impolite ๐ The various help channels are in the "available help channels" topic ๐๐ฟ
Oh...
Better to show some effort I mean
Yea lol i got to the function but that al.
Description
A small clarification about our requirements for # fmt: on/off, prompted by #2985 (does not fix).
Checklist - did you ...
- [x] N/A Add a CHANGELOG entry if necessary?
- [x] N/A Add / update tests if necessary?
- [x] Add new / update outdated documentation?
jI
hello, is there any easy way to get black and isort working nicely together in a github workflow?
just run one after the other
got it
since it's in CI, I suggest running both without any diff flag and running git diff after both complete so that one can see what changes need to be made to make both black and isort happy
isort has a black-compatible profile to make sure they don't fight over formatting
Yeah that's what I use in development
But I just didn't know if I could add it in a similar way in the workflow
I personally would suggest running isort after black due to some magic trailing comma stuff
if you use pre-commit and run it in CI, you get this for free btw
There's also https://github.com/omnilib/ufmt if you want something off-the-shelf. (note: it uses usort instead of isort)
I wonder if we should mention this in our docs
thank you! ๐
what is the recommended way to use black with pytest? pytest-black hasnt been updated since october 2020 and shows deprecated warnings with the latest pytest
ah looks I need to ignore the tracebacks while comparing analyses for that weird diff-shades issue
i could fix it myself and i believe there's a pending pr that fixes it but i dont want to use the pending pr because that'd involve installing a dependency from git as well as fixing myself and publishing a release could take a while
I have never used black with pytest and I don't see any warnings from black's side so I'm of little help.
ah
was just wondering if anyone knows of alternate ways to use it with pytest i guess
im curious why do you need it in pytest?
we've been enforcing formatting by making a pytest test for whether code is properly blacked
so tests fail if the code isn't formatted properly
have you had a look at pre-commit?
right, as opposed to a custom CI step that runs black check?
i have but that requires everyone who contributes to use it (which is possible to enforce, but kinda hard)
what do you mean?
or a tox run
we use tox to test multiple python versions, can it test for black formatting too?
yup
surely you can just make an environment and run black there, no?
as you would any other tool
.github/workflows/lint.yml lines 27 to 28
- name: Lint
uses: pre-commit/action@v2.0.3```
in our case this runs precommit as part of the CI suite, which in turns run black check
oh github lets you automatically apply code before a merge?
no, you just get a red signal saying your formatting is broken
same as a broken test
so I guess it would be: PR red flag -> go for CI, local test run -> go for tox env
you can use pre-commit.ci to have fixes automatically applied, some folks might like it, but it can be nice
sounds great, i'll google that!
hey friendos
is there a way to run black on commits automatically?
so I can check with a pr if it's ok but run if black thinks it's sus?
the aforementioned pre-commit!
Can you help me set it up?
here's our config: https://github.com/psf/black/blob/main/.pre-commit-config.yaml#L7
.pre-commit-config.yaml line 7
- id: black```
I'm sure pre-commit has lots of good example resources
name: CI
on: [push, pull_request]
jobs:
black:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Run linter
uses: psf/black@stable
with:
options: "--line-length 120 --check"
src: "."
this is what I use right now
Oh do you mean running it online instead of before every commit locally?
oh lmfao thats a concise way to phrase the question i just had
the convergence
I want black to be ran online if possible
with only the stuff it needs
in the speacil .yml for it
or does it need to go into this one?
then a similar job with black --check will work just fine!
what do you suggest I do in this?
black . 120?
I don't know what to do to autoformat on commits?
oh sorry, I misunderstood
I am also a bit overwhelmed rn
I don't care if I make it autoformat prs and stuff, I just want it to check the workflow if it fails, to autoformat to 120
I'll note that you should define version right now since the action version is independent from the black version
So to reiterate, you'd like for your CI run to automatically format the code with black and produce another commit to a PR?
Yes
Or just check if the code is formatted correctly?
if it fails
.... I should change this, cause it's dumb.
JD, that isn't what we are asking for
I would rather it autoformat when the pr fails and updates
Who are "we" :D
@errant barn He misunderstood, he just want it to autoformat on commits.
Me and some other ppl in his bot support
only one person to be specific with me
I think Autoformatting on prs and stuff if black fails is better tho
I'm so confused
We just want autoformat when new commit comes.
Not PR commit or anything, just repo commit
so on the main / master branch only?
that works for me but I still want the workflow check
yeah that
So in essence:
MAIN / MASTER:
- run black
- and push changes in a new commit
EVERYTHING ELSE:
- run black
- do nothing but fail the workflow
I would to keep my workflow though for new users
yes
yup
as I now no longer need to push a black fix
and it's done automatically
will it commit if black passes, I would rather it not commit if it passes with flying colors, i.e. black has no change?
Well given I don't think a prebuilt solution exists, it's going to be custom.
What are you guys talking about
Is anyone gonna answer my question
and you know not commit when there's no changes
well it is possible, but it requires some custom GHA logic
workflow stuff
committing formatted code when commit in main/master branch, failing in workflow if black sees its not formatted
I am a big newbie to workflow
if black pushes a commit to main, should that workflow fail still?
what do you mean ?
We are talking about how to run black in CI according to these requirements @mint barn
For main, if black changes a file (and then pushes a new commit as agreed upon) should the job be marked as failed still?
What is Cl
eh, whatever is simple is fine
continuous integration, basically running automated checks against a changeset before deployment
this kind of workflow is not simple though
I've worked with the lighter workflow of the year and a half years old when he was the first
pre-commit could make it easier, if you're open to having the check and correction locally
well, how about,
MAIN/MASTER:
- format, then push change to new commit
only
Guys how about both
Find a way to make it with both
There's no way to get a workflow check?
you can't like
check commit
then recheck?
Make 2 different ones
I am working onn it
name: CI
on: [push, pull_request]
jobs:
black:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Run linter
uses: psf/black@stable
with:
options: "--line-length 120"
src: "."
- name: Commit & push changes (main only)
if: github.event_name == 'push' && github.ref_name == 'main'
continue-on-error: true
run: |
git config user.name "github-actions"
git config user.email "github-actions@example.com"
git add -A
git commit -m "[ci] Autoformat with black"
git push
- name: Fail job if changes were made (PR only)
if: github.event_name == 'pull_request'
run: git diff-index --quiet HEAD -- || (git diff && exit 1)
@glacial swan this should work
this is what the auto pushed commit looks like: https://github.com/ichard26/testblackaction/commit/581c3961a16908fa0052657871bbef25433bde76
I'm getting pretty decent at writing gha workflows ๐
not that I recommend what I shared as I provide no guarantees, but if it works I guess why not
so update ci.yml?
And this should work?
I just took the original yaml file you gave us earlier and added the bits to support what you wanted
@dense jungle this weird diff-shades behaviour where it's claiming changes exist when it shows none should be fixed now: https://github.com/ichard26/diff-shades/commit/bd7f033cda81175be2c46b381c02269dfa3bfe03
you should use an email of a bot in order for it to not show on the Contributors tab in repo's Insights
what branch are you pushing to and is this part of a PR?
I'll note that since the job is run twice (once for the push event and another time for the pull event) on local PRs, the one triggered by the push event is kinda useless / ignored / ran without doing anything meaningful
GitHub unfortunately still doesn't provide any good way of cancelling / skipping jobs triggered by the push event when the pull_request event (and its copy of the jobs) is also going to trigger
You can block push events from firing on all branches except main, or skip the pull_request job if it's coming from the target repository but either of these are not ideal.
Anyway I got some work to do now, so I got to go.
what is the problem?
No
it looks to work
I mean
does this look fine to you?
oops
no it doesn't autoformat
the problem here is it doesn't push the new version
looks a bit complicated, i got this to work for my similar use case:
name: Lint
permissions:
contents: write
on:
push:
branches:
- main
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Run black check
uses: psf/black@stable
with:
options: "--check --diff"
- name: Run black format
if: failure()
uses: psf/black@stable
with:
options: ""
- name: Commit black format
if: failure()
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "Apply black to code"
this only runs the commit for fixing code with black if there was any code to fix in the first place
and it only runs for pushes to the main branch, but that's easy to change
can you help have this actually push to master?
I can even dm the github if you want
one final is that it pushes when on master anyway, can we prevent that?
What?
yay, thanks!
Yea that's expected, that's why there is continue-on-error
so it doesn't mark the job as failed, only the step
This is annoying though
Look, I can fix it tomorrow, but I'm busy now.
ok
Can you please dm me a fix when you are available if possible ?
Thank you in advance
@glacial swan what's the problem you're having? I might be able to help
this
the check passes
but I get a black
error like this
can you link to the workflow on GitHub?
name: CI
on: [push, pull_request]
jobs:
black:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Run linter
uses: psf/black@stable
with:
options: "--line-length 120"
src: "."
- name: Commit & push changes (main only)
if: github.event_name == 'push' && github.ref_name == 'master'
continue-on-error: true
run: |
git config user.name "github-actions"
git config user.email "github-actions@example.com"
git add -A
git commit -m "[ci] Autoformat with black"
git push
- name: Fail job if changes were made (PR only)
if: github.event_name == 'pull_request'
run: git diff-index --quiet HEAD -- || (git diff && exit 1)
Here's the workflow file
That's both
hm maybe it fails the workflow only if the last command failed?
the workflow passes
I just don't want to see black complaining
if it can't commit as it's an empty commit
on the run you linked Black didn't seem to want anything changed
25 files left unchanged.
then you need to write some more complicated shell script than you have
could also consider using pre-commit.ci for this, it takes care of applying the changes for you
no, that runs in CI
despite the name it doesn't require people to use local pre-commit hooks
so it just autoformats on every commit unless it good?
yes

For some reason, the shorter line is formatted but the longer one isn't
To Reproduce
These lines of code:
PW_PATTERN = "08 00 00 00 09 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 00 00 00"
ID_PATTERN = "01 00 00 00 0B 00 00 00 0D 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 00 00 00"
Will be formatted like this:
PW_PATTERN = (
"08 00 00 00 09 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 00 00 00"...
Should I expect black to move the key to the next line assuming the default line length of 80/88?
GGG = {
"12345678901234567890123456789012345678901234567890": "12345678901234567890123456789012345678901234567890"
}
Describe the bug
# fmt: on and other comment-only lines are removed before a line with # fmt: skip.
To Reproduce
# fmt: off
1
# fmt: on
# comment
1 # fmt: skip
The format...
Description
This PR is a continuation of #3034.
The end goal of thus PR is to move all cases in the tests/data directory into subdirectories and remove all hardcoded cases lists.
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
HUGE! ๐
Some comments below. Do you think changing the read_data interface (and I guess that would mean moving notebooks as well) would still be relevant and better? Honestly, not a big deal to me.
Description
VSCode announced a new extension for Black in their update notes for version 1.67.0, this PR adds a sentence to the editor integrations docs about this extension.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Thanks again! Overall, I like the categorisation and it's nice that most individual test functions are now gone!
Having a directory for a single fast is a bit awkward ๐ how about misc? No biggie tho, feel free to ignore if you think it's more natural there. Also, it could be nice to use the automatic .py appending consistently.
Seems helpful for readers. Please just fix the lint.
<!--
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 `...
5d5b731 Bump docker/setup-qemu-action from 1 to 2 (#3056) - dependabot[bot]
ba21a85 Bump docker/build-push-action from 2 to 3 (#3057) - dependabot[bot]
4af87d8 Bump docker/login-action from 1 to 2 (#3059) - dependabot[bot]
7f03313 Bump docker/setup-buildx-action from 1 to 2 (#3... - dependabot[bot]
Describe the style change
Black did made this unusual ugly change to my code after I made the string longer.
Examples in the current Black style
webbrowser.open(
"https://github.com/Matiiss/" f"pygame_examples/tree/main/pgex/examples/{name}"
)
Desired style
webbrowser.open(
"https://github.com/Matiiss/"
f"pygame_examples/tree/main/pgex/examples/{name}"
)
Additional context
The ...
do you know how I can fix Dubugger?
Python type checkers supports enclosing type annotations in a string to make forward references possible. Although from __future__ import annotations makes that unnecessary in type annotations, it's still needed in type aliases.
Example:
# All these are equivalent from the point of view of the type checker
x: "Union[A, B, C, D]"
x: Union["A", 'B', """C""", '''D''']
x: Union[A, B, C, D]
# Same here
y: TypeAlias = Union[A, B, C, D]
y: TypeAlias = "Union[A, B, C, D]"
y: Type...
Describe the style change
I have an assert statement that checks a condition on the last element in an array. To me what black does to the statement makes it less readable:
assert self.ref_transitions[-1].terminal.all(), "Last ref transition must be terminal."
Examples in the current Black style
assert self.ref_transitions[
-1
].terminal.all(), "Last ref transition must be terminal."
self.initial_state = sel...
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Apologies if this is too trivial, the assert was just kinda bothering me
Totally agree here. Thanks!
Image to ASCII (Pillow Required)
For it to work, there has to be an image with the python code in the same folder and you have to typeout its full name + extenion.
import PIL.Image
# ascii characters used to build the output text
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", ".", "1", "2", "3", "4", "5", "6", "7", "9", "8", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "T", "U", "V", "W", "X", "W", "Y", "Z", "0", "`", "~", ",", ".", "/", ";", ":", ";", "[", "]", "|", "-", "_", "="]
# resize image according to a new width
def resize_image(image, new_width=100):
width, height = image.size
ratio = height/width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
# convert each pixel to grayscale
def grayify(image):
grayscale_image = image.convert("L")
return(grayscale_image)
# convert pixels to a string of ascii characters
def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=100):
# attempt to open image from user-input
path = input("Enter a valid pathname to an image:\n")
try:
image = PIL.Image.open(path)
except:
print(path, " is not a valid pathname to an image.")
return
# convert image to ascii
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
# format
pixel_count = len(new_image_data)
ascii_image = "\n".join([new_image_data[index:(index+new_width)] for index in range(0, pixel_count, new_width)])
# print result
print(ascii_image)
# save result to "ascii_image.txt"
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
# run program
main()
not the channel for it mate
Description
I believe it would benefit users if this doc had more examples on how to specify multiple files/directories.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
hi everyone,
any idea why my black is not setting the trailing comma? It is doing the line break but not setting the trailing comma itself.
my pyproject.toml has only 2 lines:
[tool.black]
line-length = 120
exclude="file/path/"
is it only on a single line?
I have a dict like this
{
"a": fun(msg, "ts"),
"id": ...,
"key": ..., "created": ...
}
and running black . in console will make the linebreak to
{
"a": fun(msg, "ts"),
"id": ...,
"key": ...,
"created": ...
}
but its not setting the last comma at the end
the problem was a comment on the next line
https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADmAHRdAD2IimZxl1N_Wm_vzTQ-P7e88-HPpthubCyLPup10IjvULL9Te6KZ1NodUgQMtz1NLUGAc5rjTKK_QogZJuLtXRH2sY5WOk6D72XAqkz1z1husCxzNbP5ioWHtGyI7H0HAVp5zntQmX8C62vRP-twtlIMnwtAB0bycSlKUlRAAGQAecBAACY-DmpscRn-wIAAAAABFla
Playground for Black, the uncompromising Python code formatter.
hmm, oh!
(cool website btw with the black example formatting
and putting it onto the same line does produce the trailing comma
the comment I mean
true, so I guess I found a bug ๐
yeah, at least I can't come up with a reason as to why that would be :D
feel free to submit if you'd be so kind!
man, I dont envy you developer dealing with all these edge cases xD
:D feel free to also contribute ๐ envy is a grave sin you know
sure, I can open a ticket on github about it.
๐ feel free to also contribute ๐ envy is a grave sin you know
I might actually give it a try ๐
or which way it goes, anyhows
thank you for your help and have a nice day ๐
cool, we'll be there to help!
you too
Thanks - I like the example, but I feel .py.bak we should ignore by default ... So do we want another example?
sooo, I got the black dev environment locally up and running (great job with that btw, worked on the first try) and set up the test case that is failing, and went into black._format_str_once with a debugger to understand what is happening
I landed at black.linegen.delimiter_split() where I think the source of the issue lies, but I am not sure about that.
I got to this chunk of code, where the current_line is checked and always the last leave is selected and checked. If I understand correctly by some backwards looping through the line leaves
When I let the debugger iterate and always check, what current_line.leaves[-1] prints, it prints the last lcomment line # "longkey": ...
Yo! Lemme try, but small disclaimer: I'm not really an expert on the formatting code either
also, great to hear that the initial process was smooth :D
It seems like the candidate location for a fix, but since it's spelled out in the code I think we ought to make sure that this is unintended first
i.e. submit an issue and discuss more there
I will do that, ๐๐
sooo i've been playing around with this: https://zsol.github.io/format/
it's client-side black ๐
Webasm?
very creative use of mocking
fyi, two single quote issues (#633, #1794) have been necroed :P
Describe the bug
When running black on a dictionary with a comment, a trailing comma is not set correctly
The example
{
"a": fun(msg, "ts"),
"longggggggggggggggid": ...,
"longgggggggggggggggggggkey": ..., "created": ...
# "longkey": ...
}
is being formatted to
{
"a": fun(msg, "ts"),
"longggggggggggggggid": ...,
"longgggggggggggggggggggkey": ...,
"created": ...
# "longkey": ...
}
where the , is missing after ` "...
Can I share that link to gh repo?
I've updated this, sprinkled some delight on it and tweeted about it
that's how products are developed right?
lol you're not that wrong
I'm just doing regular web development with pure JS, HTML, and CSS right now ๐
you could be writing python instead! ๐
I only have to clean up this messy JS so I think I'm good for now. Anyhow, how long did that website take you?
you mean to write it?
yeah
about 3 hours net total
oh wow that's not long at all
yeah and I had no idea how to use py-script before ๐
not counting my wife's pixel-pushing that resulted in the wonderful css
haha, it's wonderful
how is the performance would you say?
it's obviously going to be slow as this is first-gen tech, but I have a lot of stuff open right now (discord's and vscode's electrons are not being kind to my CPU)
Much better than I expected, that site reformats on every keypress and it's usable
oh that's great to hear
who else loves tkinter
Version information
pre-commit version: 2.19.0
> pre-commit --version
pre-commit 2.19.0
pre-commit black version: 22.3.0 (https://github.com/ludwig-ai/ludwig/blob/master/.pre-commit-config.yaml)
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
name: black
command line black version: 22.3.0
> pip show black
Name: black
Version: 22.3.0
Summary: The uncompromising code formatter.
Home-pa...
hmmm the first thing that comes to mind would be mypyc
.. which would be concerning
can't reproduce the issue
os or python version dependent?
no idea, couldn't reproduce this either
!format
String Formatting Mini-Language
The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format().
Take a look at some of these examples!
>>> my_num = 2134234523
>>> print(f"{my_num:,}")
2,134,234,523
>>> my_smaller_num = -30.0532234
>>> print(f"{my_smaller_num:=09.2f}")
-00030.05
>>> my_str = "Center me!"
>>> print(f"{my_str:-^20}")
-----Center me!-----
>>> repr_str = "Spam \t Ham"
>>> print(f"{repr_str!r}")
'Spam \t Ham'
Full Specification & Resources
String Formatting Mini Language Specification
pyformat.info
how do i format my code
!raw 975377672714731530
== Raw message ==
\`โ`โ`โpython
print('test')
`โ`โ`โ
sick :D
Guys, I have this code:
oldfile = open("FILE-%s.csv" % (state),'r')
newfile = open("FILE2-%s.csv" % (state),'w')
newfile2 = open("FILE3-%s.csv" % (state),'w')
for line in oldfile:
if re.search('\$1,5',line) or re.search('\$1,6',line) or re.search('\$1,7',line) or re.search('\$1,8',line) or re.search('\$1,9',line) or re.search('\$2,',line) or re.search('\$3,',line) or re.search('\$4,',line) or re.search('\$5,',line) or re.search('\$6,',line) or re.search('\$7,',line) or re.search('\$8,',line) or re.search('\$9,',line) or re.search('\$10,',line) or re.search('\$11,',line) or re.search('\$12,',line) or re.search('\$13,',line) or re.search('\$14,',line) or re.search('\$15,',line) or re.search('\$16,',line) or re.search('\$17,',line) or re.search('\$18,',line) or re.search('\$19,',line) or re.search('\$20,',line):
newfile.write(line)
else:
newfile2.write(line)```
I was trying to filter out any lines which contains $1,5xx,xxx, $1,6xx,xxx,... all the way up to $20million, meaning filter out anything that have value of $1,5 million and up. Now, I realize this is not how to do it. Because it's also removing $1,500, $1,600... $20,000 (not the million 7-digit value).
Not sure how to improve /fix the above
this is a wrong channel to ask
It seems like you're asking a coding question, you should read #โ๏ฝhow-to-get-help
dang, just realized that now sorry
๐
is this on topic for this channel @mint barn ?
what is
that eval command
what eval command
Ugh whatever. Just don't do that again.
i have no idea what ur talking about ๐ ๐
Please refrain from advertising projects on this channel, it's for Black development
Currently (black 22.1.0) it is not possible to turn off colored output, in particular in the summary at the end. Please provide a simple way to turn color off, preferably via one of the environment variables PY_COLORS or NO_COLOR.
Describe the bug
A fresh conda env with minimal install of
- black
- jupyterlab
- jupyterlab_code_formatter
still shows the long known (#2681 , #1143) "Writing grammar tables.... Writing failed" bug:
Generating grammar tables from /home/maye/mambaforge/envs/black_bug/lib/python3.10/site-packages/blib2to3/Grammar.txt
Writing grammar tables to /home/maye/.cache/black/22.3.0/Grammar3.10.4.final.0.pickle
Writing failed: [Errno 2] No such file or directory: '/home/maye/.ca...
Describe the bug
When a # fmt: skip is on a given line, any preceeding comments directly above the given line will be deleted.
To Reproduce
For example, take this code:
# Comment about this line below
data = [ True, True, False] # fmt: skip
$ black file.py --target-version py310
The resulting file is:
data = [ True, True, False] # fmt: skip
Expected behavior
The comment line should have remained uncha...
ugh, we still can't run CI on Python 3.11-dev on GHA for some reason
creating build/temp.linux-x86_64-cpython-311/aiohttp
gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/home/runner/work/black/black/.tox/ci-py/include -I/opt/hostedtoolcache/Python/3.11.0-beta.1/x64/include/python3.11 -c aiohttp/_websocket.c -o build/temp.linux-x86_64-cpython-311/aiohttp/_websocket.o
aiohttp/_websocket.c:198:12: fatal error: longintrepr.h: No such file or directory
198 | #include "longintrepr.h"
| ^~~~~~~~~~~~~~~
compilation terminated.
error: command '/usr/bin/gcc' failed with exit code 1
[end of output]
I thought the new Cython release today was supposed to fix this ... >.<
gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/home/runner/work/black/black/.tox/ci-py/include -I/opt/hostedtoolcache/Python/3.11.0-beta.1/x64/include/python3.11 -c frozenlist/_frozenlist.c -o build/temp.linux-x86_64-cpython-311/frozenlist/_frozenlist.o
frozenlist/_frozenlist.c: In function โ__Pyx_AddTracebackโ:
frozenlist/_frozenlist.c:432:62: error: dereferencing pointer to incomplete type โPyFrameObjectโ {aka โstruct _frameโ}
432 | #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
| ^~
frozenlist/_frozenlist.c:7127:5: note: in expansion of macro โ__Pyx_PyFrame_SetLineNumberโ
7127 | __Pyx_PyFrame_SetLineNumber(py_frame, py_line);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
error: command '/usr/bin/gcc' failed with exit code 1
[end of output]
looks like the interpreter core optimisation work still breaks frozenlist
does aiohttp distribute the generated .c files?
if so they need to recompile and release
I'd guess not given the traceback file is build/temp.linux-x86_64-cpython-311/aiohttp/_websocket.o
although tbf I don't know how included C would work when being built from a sdist
I checked, there's .c files in the sdist
yeah me too
my only comment on https://github.com/psf/black/pull/3035 is that if we remove immediate newlines after blocks, that might effectively decide black's stance on newlines after class signatures nevermind, please see below!
I don't remember enough of the discussion in regards to classes and following newlines, but I do know they are somewhere in the issue tracker
I'm still +1 on the change though.
hmm, actually black already has an opinion about this :)
--- test.py 2022-05-18 16:45:22.675999 +0000
+++ test.py 2022-05-18 16:45:23.703591 +0000
@@ -1,10 +1,10 @@
class A:
-
def func():
pass
class B:
"""docstring"""
+
def func():
pass
!remind 5H audit recent code style changes to make sure our style documentation covers 'em
Your reminder will arrive on <t:1652910448:F>!
Here's your reminder: audit recent code style changes to make sure our style documentation covers 'em
[Jump back to when you created the reminder](#black-formatter message)
Description
This PR replaces the normal Discord invite, with the vanity one.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
that invite link is for the whole server, not this channel specifically as is currently
Nice! I quite like the idea of having atomic test cases in each file, but it's different from the current setup where a category of tests is contained in a single file (or a few files). I don't feel strongly about it, but perhaps it would be worth considering just to be consistent.
The doc is also good, although in my personal opinion we could keep it terse since we have similar generic newline speak in the ["current style" doc](https://black.readthedocs.io/en/stable/the_black_code_style/c...
This issue is not a feature request, but it concerns about testing. Please remove the "enhancement" label
Description
We've made a lot of progress improving the testing process in #3034 and #3062.
A problem that still remains is that the existing cases data files are ENORMOUS. those data files can contain up to 300 lines (and even more), which is way too much for a test. Cases files, and tests in general, should be short and concise in order for us to track down errors as e...
!raw 975377672714731530
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Hola!
I really like black and we use it in our project at work.
We also recently added http://www.pydocstyle.org/ to our checks. A feature I wish black would have is to format D400 - First line should end with a period . If I create a PR that autoformats a period on docstrings, what is the probability for it to get accepted?๐ค
I'd be hesitant about that. What if it ends with a question mark, or someone uses a docstring parser that doesn't want the first line to end with a period?
The pseudocode would be: If last_char not in {'.','?','!'':'}: add('.'). And pep257 clearly states The docstring is a phrase ending in a period. https://peps.python.org/pep-0257/#:~:text=The docstring is a phrase ending in a period.
Python Enhancement Proposals (PEPs)
Black's aim is to make no changes to AST
If you want to automatically make changes like this, you should probably consider other tools
Instagram's Fixit perhaps?
Hmmm, good point! We also use pre-commit, so I think my other alternative would be to make a standalone D400-autofixer... ๐
Yeah
And a ping 1 2
@bright glacier thanks for diff-shades!
sigh, OK so these notification settings will not work. Thanks for the messages!
Describe the bug
Black generates an INTERNAL ERROR with a file that has a docstring that contains a backslash with a trailing space character. Removing the trailing space solves the issue.
To Reproduce
Create a file file.py with the following content. Note, the 5th but last line (i.e., just above the line with other option) contains a trailing space after the backslash!
def foo():
"""
Some description
['some option'...
Guys how to enable black formatter on new projects in vsc? I have it in User Settings but on new project its not working, i installed it on project venv.
when i use it from terminal on file it is working, but cant get it owrking on save in vsc on new project
- How does your workspace-settings file look like? 2. - What is the output of Python in vsc when you run autoformatting? Look for the output tab between problems and terminal and select Python?
Also, you probably just forgot to set python interpreter path, ctrl+shit+P -> select python interpreter and select your .venv
My workspace settings are clean - though it will use my user settings?
I have venv python interpreter selected
Did you already pip install black in your .venv?
And setting VSCode to format on save
yes i installed but didnt set the format on save
though this settings will be imported from my user settings
yeah that solved thge problem but do i have to set this on every new project?
I think you need install black for every .venv, but for setting u don't if you have login with github in vscode the setting will sync automatically
If you look at output->python you can see what vscode executes. eg: ~/code/py/**/.venv/bin/python -m black --diff --quiet ~/code/py/***/bulletin.py
The VSCode team is planning to remove the formatting integration with Black in the main Python extension eventually, but we can deal with that later when it happens :)
Nice to see you around @laundmo. Hope you've been doing well! Thank you for the PR!
Describe the style change
Replace (foo) with foo when unpacking, where foo is an expression.
Examples in the current Black style
points = [(1, 2), (3, 4)]
for (x), (y) in points:
print(x, y)
Desired style
points = [(1, 2), (3, 4)]
for x, y in points:
print(x, y)
Often as result of refactoring I end up with f-string with no
{substitutions}, and my editor (integrated with flake8) keeps
reminding me about it.
With some stretch one can argue that this is actually formatting issue
and as such within scope of black(1). Would you be interested in patch
that implement this proposal?
print(f"Hello")
to become
print("Hello")
Description
As promised, I came with patch that mostly does what is discussed in #3081.
Code quality is back-of-envelope, and not all tests are converted. I will fix
it once we decide what to do with the most major issue:
Black produced code that is not equivalent to the source
I can't argue that it is very good and valuable sanity check, and just turning
it off seems reckless. Ideas?
Is your feature request related to a problem? Please describe.
Black currently does not format Doctests in Docstrings. This issues was reported in https://github.com/psf/black/issues/745 which was superseeded by https://github.com/psf/black/issues/144. As the latter was closed though, nothing was done about the Doctests.
Describe the solution you'd like
I would be keen for black to format Doctest.
For example, given the following Python Doctests code:
@dense jungle was this you? ๐
it's very useful ๐
(the other pageload is probably some bot)
for pyanalyze I have a similar workflow to black where the PR number goes in the changelog, so I bookmarked the page
Ah neat, Python Discord is starting to use the same changelog workflow too so now I have four main users ๐
I rewrote the codebase a week-ish ago; it was my first serious webdev project.
I think I only learned about the url parameters because you mentioned it here at some point, that was a big usability improvement for me
Yeah it's an open issue to advertise that feature better. Someone did come by and make Next PR Number update the URL to include the query parameters if you do a query which helps a little bit.
I should just add a little lightbulb admonition somewhere that mentions the URL query parameters
webdev is just โจ great and totally not soul-suckingโจ
this page has not helped: https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block
Description
This change introduces the Pants build system to the Black repo, on an experimental basis.
It does not change any of the existing build mechanisms for running tests, formatting, linting,
typechecking, building distributions etc. Developers in this repo can remain unaware of Pants if they choose.
Others may be interested in playing around with it.
For context: While chatting with @ambv at PyCon 2022 he expressed interest in seeing wh...
hey everyone, kindly pinging again about https://github.com/psf/black/pull/3035
is there anything missing from this PR? can we merge it?
Would really like to start using it in Preview mode ๐
As you mentioned in the last comment, we'd still need at least another review. We've agreed it's the better style, but an approving review is still needed. Also, still no comments about removing the class body newline. And to that end: did you consider the effect of previous code wrt. defs along with class bodies? Which is line 505 in the diff.
Hey @errant barn , I pinged it here so other reviewers could take a look at it ๐ Wasn't sure if this is the right place or I should have just add another comment in the PR (please let me know for next time!).
Surely this needs more review. No questions about that
That's ok, we're all here ๐
If there's something to discuss then it's better to do it on the issue, so that we leave the paper trail
I still think that classes should be an exception to the rule and should still be formatted according to the existing rule, due to the example I presented there
Fair, although personally I prefer to remove them ๐๐ฟ but what I meant was: defs trigger the previous formatting as well. So are there similar exceptions there?
I agree that further discussions should be in the PR. This was just a gentle ping ๐
I'm not sure what you mean. If you could please explain it better in the PR itself, I would really appriciated it
Actually, going through the code once more addressed my concern already! So don't worry about it
Provided that we agree to remove newlines in class bodies, I think this would be good to go!
Hi,
Could anyone please tell, how to add exclude folder in the setup.cfg
Following does not work:
[black]
exclude = folder/example/some_folder/
But this one works:
black --check . --exclude=folder/example/some_folder/
Hi,
I have a project with precommit hook that calls [black --check --diff] and fails commit on non-empty diff.
Collegue of mine suddenly added space after last character in line but diff looks confusing:
-)
+)
I could see the source by checkout his branch and running black over it but this is a long way.
Could black show trailing spaces in some explicit way? It will be appreciated even by specifying some CLI option.
Thank you.
Describe the bug
Black should put parentheses and wrap this tuple over multiple lines:
def asdf():
for item in items:
yield item, "this is a really long string describing item. you'd expect black to put parentheses around the tuple."
To Reproduce
Resolved now โจ
It probably shouldn't have taken 79 insertions(+) and 10 deletions(-) but oh well lol
some my suggestions:
- format content of annotations in quotes:
x: "Union[X,Y]"->x: "Union[X, Y]" - replace
'X'->Xin annotations iffrom __future__ import annotationsenabled or python>=3.11 - remove
from __future__ import <smth>if this future import is pointless for target python version
All of those suggestions sound reasonable at first sight, but all of them are also AST-unsafe and I'm wary of adding more unsafe transformations.
We could add a --ast-unsafe flag or whatever, but that would hurt black's goal of minimizing configurability
just noticed that black can format match-case syntax, cool!
Given we maintain our own CST LL(1)ish parser, we can use whatever hacks we like to support PEG syntax lol
not exactly maintainable, but welcome to an aging codebase
These requests keep coming, it could be useful to decide this one way or the other
Is this formatter avilable for pycharm?
We often get proposals for formatting changes that could be useful, but that change the AST or are otherwise unsafe. Examples include:
- Import sorting (#333)
- Formatting stringified annotations (#3067)
- Dropping useless f-strings (#3081)
- Aspects of docstring formatting (#144, #2150)
not (x in y)(#212)
Many of these proposals make sense as an extension of Black's mission to create a single, consistent style for Python code, but users have legitimate concerns about the safet...
^ here's one solution
Looks good, just some small feedback.
Would also be good to have tests for match/case.
9fe788d Add more examples to exclude files in addition ... - ysk24ok
I gotta say I like reading these GH embeds as a super duper condensed summary of what happened. Sometimes I'm too lazy to open 13 emails or whatever ๐
@dense jungle seems like an ast bug still. Where does peephole optimization and constant folding fit?
yeah I assume it gets optimized away later
but IIRC ast.parse is before the peepholer
ast.parse("1 + 1") also doesn't get constant folded
Black's promise should probably only apply after peephole and constant folding
f"ABC" r"ABC" and u"ABC" all make the same pyc?
0 RESUME 0
1 2 LOAD_CONST 0 ('abc')
4 RETURN_VALUE
>>> dis.dis('r"abc"')
0 RESUME 0
1 2 LOAD_CONST 0 ('abc')
4 RETURN_VALUE
>>> dis.dis('u"abc"')
0 RESUME 0
1 2 LOAD_CONST 0 ('abc')
4 RETURN_VALUE
I think black should promise the same pyc and not worry about the ast
The pyc doesn't sound very stable imo
I feel like that's a harder promise to implement since the pyc format is much less stable
If we can simply say "ast.parse is the same before and after, no ifs or buts", that's a much more convincing promise
The same ast means the same pyc right? So it's a looser promise?
It's harder to check for
Maybe there's some IR that cPython could commit to
That feels like a lot of work for very little gain
The cases where we could make ast-unsafe changes that are pyc-safe are pretty obscure
f-string normalisation
And under my proposal, we'd still do minor AST-unsafe changes (like useless fs) by default, we could just offer an additional mode that guarantees zero AST changes
I'd have expected this to be removed in the AST phase
report it to CPython ๐
.>
f-strings being integrated into the peg parser seems like this could get fixed up
r/f/u prefix is a CST concern imho
Black already drops u prefixes for what it's worth
Does the AST expose u prefixes?
no
Hmm redundant f prefixes is definitely an ast bug then
Are redundant r prefixes in the AST?
no, the AST just gives you the string as it would appear in Python
no triple quoting either
Points to redundant f strings being exposed to the AST being a bug
And related to the fact that f-strings get parsed in a second pass
Yes, it's definitely unexpected. When I tried it I expected it to be the other way around, because we removed fs from implicitly concatenated strings and that is AST-safe
"Module(body=[Expr(value=JoinedStr(values=[FormattedValue(value=Name(id='x', ctx=Load()), conversion=-1), Constant(value='a')]))], type_ignores=[])"
>>> ast.dump(ast.parse('f"{x}" f"a"'))
"Module(body=[Expr(value=JoinedStr(values=[FormattedValue(value=Name(id='x', ctx=Load()), conversion=-1), Constant(value='a')]))], type_ignores=[])"
Seems like a public python function to peephole optimise an ast and return a new one would be popular
I feel the name is fine. Lets just type annotate to get CI passing and we can merge this to have a starting place and let others improve it as people find time to do so.
e.g. unittests ...
<!--
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 `...
Black is not a linter so nope
And don't worry you have found the right place!
Yes. You could run black manually with the --diff to see what would be changed but that's it
What would you want to see?
What kind of problems?
Yeah that's out of the picture since black doesn't operate by first detecting issues and then fixing them. It only knows how to turn some code into properly formatted code. Kinda like setting something in a silicon mold
The line (number) would be a lot easier but that's still unlikely
I have no idea, I don't use VSCode often and I have never really used its formatting integration
I don't think format on type is supported by Black at the moment
(nor any other python formatter I'm aware of)
Would this be possible if black switched to libcst?
not really
at the moment
well, it depends. If you wanna format unfinished files while you're typing, that would need an error-recoverable parser
which neither libcst nor black has at the moment
there are plans for libcst to gain this feature though
there are many other considerations though. People often use Black to detect syntax errors; that wouldn't be as easy with such a solution
People use black to detect syntax errors
?
Why is this? Error resilient parsing still emits errors, it just requires a good recovery strategy, does it not?
yeah and it'd require rewriting Black
Ooh that's quite interesting. Is libcst generated from a grammar or is it entirely handwritten?
the parser is generated using PEG at the moment
got it, got it
oh yeah, I remember looking through that. I haven't had a very good experience with autogenerated parser and good error reporting/resilience.
well, CPython has a generated parser ๐
it's the only mainstream language implementation I know of that doesn't hand-roll its parser
doesn't that still only find a single error at a time?
yep
I mean it technically can find multiple errors but just reports the furthest one
yeah, for the python parser I've been writing, I've pretty much resigned myself to handwritten for error recovery >.<
I honestly don't know, beyond "I felt like it"
best reason 100%
does black operate directly on the libcst CST?
I wish
sorry, not libcst, but whatever other lib (blib2to3?)
Describe the style change
If a function/class is defined at the start of a non-scoping indent (e.g. if, for) a blank line is inserted before the function.
I would like this removed, since:
- If an indent is scoping (e.g.
def,class) no blank line is inserted, style should be consistent. - I believe this is redundant since the indent already separates the function definition well enough.
- Blank lines are not inserted for normal code, so I don't see the point of adding i...
I guess it works, but when you type your file has invalid syntax and black cant do anything
Close, but one last error ... Lets prefer to use types from the typing library :)
It's easy to run mypy locally or run pre-commit to run the CI
Today black allows both of these:
a = f"{None}"
b = f"{ None }"
> black test.py
All done! โจ ๐ฐ โจ
1 file left unchanged.
Perhaps an opinionated tool should have an opinion here.
How can I make black not go insane on lists like this for command line arguments
I'd rather it use word wrap in this example than add 40 lines into my program.
You will have to disable black via # fmt: off/on or # fmt: skip
I'm still interested in using black, just specifically not on this one list.
Hence the formatting control comment ^^
Oh, didn't know that was even a thing. Didn't understand what you meant ๐
Thanks!
๐ ty
Btw this example was also helpful, as I had originally tried to use # fmt: skip on the line prior like you would # fmt: off
Thanks again
heard of this before, but unclear on exact allowed syntax - how exactly are these detected? do fmt controls still work if the line is, e.g. a = 2 # fmt: skip (reason why), or # explanation, so we will use # fmt: off? or does skip have to be at the end and on/off the only contents on a line?
I honestly don't know. I personally will try to avoid # fmt: skip since I don't trust it
the implementation is pretty buggy and I've been meaning to improve it but obviously that hasn't happened yet
I'm pretty familiar with # fmt: off/on though
I'm team black all the way 
https://github.com/Pierre-Sassoulas/black-disable-checker
๐ my goodness
I love it
small request, i need a pep 9001 black formatter
That's certainly not a small request, that would require changing the parser that black uses a fair bit, as well as the actual formatting code.
So you'd basically need to rewrite the whole project.
How about this instead? https://pypi.org/project/flake99/
I tend to automatically generate these, or use "...".split(",")
I do too, but Iโm trying to make the code as straightforward to understand as possible.
In this context, this is simpler to understand.
@dense jungle how would you like to be credited in my mypyc blog series? I can do full name and link to your github profile, or would you like something else?
I'm still in the process of editing it, but I'm working on it again. Hopefully I can finish editing today ๐ค
Hey, I've been trying out black and find its results pretty nice for the most part, but this is something I don't quite understand; why would the compact format (single line) be considered better by black? Imho, it's less readable when passing multiple kwargs in. Wondering about a second opinion on this.
that sounds good, thanks!
you can add a trailing comma to force the parameter list to be exploded
yup I prefer the latter, btw : Embed doesn't do anything
After who knows how many hours, my mypyc series detailing the journey integrating mypyc into black is published: https://ichard26.github.io/blog/2022/05/31/compiling-black-with-mypyc-part-1/ ๐
I spent a COVID summer (and then some) integrating mypyc into Black to double performance. How was it?
This is an interesting read thanks for writing this up
Friends, bump @bright glacier's blog posts on making Black faster on Hacker News:
https://news.ycombinator.com/newest
Please don't link to the submission directly
Bumping from a direct link doesn't do anything
lol, I'm not enough of a nerd to know how to use HN. I don't even have an account there, thanks y'all
It's annoying the link has to be dug out of /newest but it's how the game is played
do you know for sure that's true? I've heard it before but who knows whether they changed the rules
I don't know anybody at Y Combinator if that's what you're asking
But it's a well known rumor at least
@bright glacier Which tool produced this graph?
I saw something like it on the discourse
I thought I linked 'em?
I skipped the important line and looked at scalene ๐
but either way I used cProfile and then used gprof2dot (the yelp fork, not the original one) piping the output into the dot linux utility
it is really useful
The blog post will fall off the first page of https://news.ycombinator.com/newest soon. Upvote it you cowards
oh no I can't find it anymore
Describe the bug
When run with python3 -m black (used by vscode) black keeps the current working directory inside sys.path which can result in a crash if there are name conflicts between black's imports and the files in the current working directory
To Reproduce
touch ast.py- Run
python3 -m black ast.py
Output:
python3 -m black ast.py
Traceback (most recent call last):
File "/usr/lib/python3.9/runpy.py", line 188, in _run_module_as_main
mod_nam...
heya, if i had some questions re: mypyc could i ask them here or is it strictly black? although i might have to do with it in the future re: async
actually i answered what i was gonna ask thru: https://github.com/mypyc/mypyc/issues/868
There are a bunch of async features we don't support async with/async for (https://www.python.org/dev/peps/pep-0492/) async comprehensions (https://www.python.org/dev/peps/pep-0530/) async ...
Hi
The latest release, 22.3.0, issue #2918, PR #2942, has broken formatting for function definition and call. In previous versions of Black the following:
def intentional_comma(a: int, b: int, c: int,) -> int:
return a + b + c
def intentional_comma(a: int, b: int, c: int,):
return a + b + c
intentional_comma(a=10, b=20, c=30)
Would be formatted to:
def intentional_comma(
a: int,
b:...
Thanks for the persistent effort here. I hope people find it useful.
I guess the only way people might find it is docs - so maybe we should add a parapgraph here (with usage examples): https://github.com/psf/black/blob/main/docs/guides/introducing_black_to_your_project.md
Happy for this to be in another PR.
Nightly CI failed due to Setup jobs failed to start
Current runner version: '2.291.1'
Operating System
Ubuntu
[2](https://github.com/redhat-performance/benchmark-runner/runs/6704381902?check_suite_focus=true#step:1:2)0.04.4
LTS
Virtual Environment
Environment: ubuntu-20.04
Version: 20220529.1
Included Software: https://github.com/actions/virtual-environments/blob/ubuntu20/20220529.1/images/linux/Ubuntu2004-Readme.md
Image Release: https://github.com/actions/virt...
meow
Describe the style change
Currently, black does not add a space after unary operators like unpacking, but does around binary operators. When operator hugging seems to contradict precedence, should black insert parentheses?
Examples in the current Black style
In all cases, multiplication occurs before unpacking, but it appears that unpacking happens first.
(*2 * (0,), 0)
(*(0,) * 2, 0)
s = (
*(0,)
* a_long_variable_or_expression_that_evaluates_to_2...
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Description
This implements my proposal for https://github.com/psf/black/issues/2543
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
I got latest Black from PyPI, and got all latest libs for it.
I got lib2to3 from
https://github.com/python/cpython
and renamed its folder to 'blib2to3'.
now I run CudaText plugin 'Black formatter' and get errors
Traceback (most recent call last):
File "/home/user/.config/cudatext/py/cuda_fmt/__init__.py", line 227, in format
res = helpers.get_props(lexer)
File "/home/user/.config/cudatext/py/cuda_fmt/__init__.py", line 148, in get_props
return self.get_item_props(i...
Describe the bug
this becomes
return (
flu(files)
.map(to_path)
.flatten()
.collect() # type: ignore
)
this.
return flu(files).map(to_path).flatten().collect() # type: ignore
To Reproduce
Run above code with these arguments:
$ black --target-version py310 -- test.py
Expected behavior
intentional parenthesis around method chains should be respected and not break into single statement.
Environment
...
what were they even thinking?

I'm glad at least they provided reasonable repro steps instead of just the error ๐
was it always like this? I know that call chains are at least somewhat preserved if they're longer than line length but did black always join it into one line if it fit?
IIRC it's been like this for a long while now
yes
Current Black code needs the blib2to3. where can I get it? PyPI doesn't have it.
I try to update Black in CudaText plugin
https://github.com/cudatext-addons/cuda_fmt_python_black
and now after update of all libs I got this (Ubuntu x64 Python 3.8.10)
Traceback (most recent call last):
File "/home/user/.config/cudatext/py/cuda_fmt/__init__.py", line 227, in format
res = helpers.get_props(lexer)
File "/home/user/.config/cudatext/py/cuda_fmt/__init__.py", line 148, in get_props
return self.get_item_props(item)
File "/home/user/.config/cudatext...
oh, wow this plugin is quite outdated
they are the maintainer of that plugin given the repo is owned by them..?
either way, I'm not sure if they know how python packaging works
CudaText plugin used this old code which didnt support Py 3.9 and 3.10
import sys
import os
import re
import json
from cuda_fmt import get_config_filename
PY_OK = sys.version_info[:2] >= (3, 6)
if PY_OK:
sys.path.insert(0, os.path.dirname(__file__))
from . import black
from .black import TargetVersion as Ver
ver35 = {
Ver.PY35,
Ver.PY36,
Ver.PY37,
Ver.PY38,
}
ver36 = {
...
I have old code from 2020 which used 'attr' lib in Black.
folder of 'attr':
$ ls
_cmp.py converters.py filters.py __init__.pyi setters.py _version_info.py
_cmp.pyi converters.pyi filters.pyi _make.py setters.pyi _version_info.pyi
_compat.py exceptions.py _funcs.py _next_gen.py validators.py
_config.py exceptions.pyi __init__.py py.typed validators.pyi
I dont see .pyc files created here! so its not used?
weirdly https://github.com/cudatext-addons/cuda_fmt_python_black seems to have a copy of Black in it
what is even going on
honestly
can we politely tell them to stop opening issues
and we're not going to fix their project for them
interestingly CudaText has nothing to do with CUDA the GPU programming thing, it's an actual text editor
written in Pascal of all things
Yeah, I was going to say the CUDA team should know Python better but nope, it's not even CUDA related
I'm running into a case where I pass a file to black e.g. black module.py but it just says "No Python files are present to be formatted. Nothing to do"
Yet when I paste the code into the playground it does format it.
What gives?
What is emitted when you pass --verbose to the command?
The file is snekbox/nsjail.py
What I have is force-exclude = ["snekbox/config_pb2.py"]
How does that match?
I have no idea but force-exclude's type is a string
oh
hence regular expression in the output
I though it was a list of regexes
In hindsight I suppose that doesn't make much sense
Ah fair enough, no worries. I wonder if the help output could be any clearer. I think we state it's a regex though.
I think i just didn't read carefully
Or maybe confirmation bias from excludes of the same file for other tools requiring a list
wonder if we could give an error if it's a list
That would be nice
Or more generally reject config files if they don't conform to the schema
Instead of having some silent behaviour
OK I really need to sit down and review some PRs.
I've been kind of out of it lately, but I have some spare 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 `pip install...
Description
Closes #3015
Checklist - did you ...
- [/] Add a CHANGELOG entry if necessary?
- [/] Add / update tests if necessary?
- [/] Add new / update outdated documentation?
Running Black on Python 3.11 produces:
% black ast_decompiler
/Users/jelle/py/venvs/311-jun6/lib/python3.11/site-packages/black/__init__.py:767: DeprecationWarning: There is no current event loop
loop = asyncio.get_event_loop()
We should fix this warning.
Makes sense and works for me.
Only enhancement I could think of is maybe showing or at least stating how to specify multiple directories - i.e. is it two --force-exclude or is it comma separated paths etc.
3.10 should also raise this warning
probably want to run pytest with filterwarnings=error
black.concurrency.shutdown is redundant on 3.9 https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.shutdown_default_executor
Installed multiple times on different project. Latest version( 22.3.0) gives the following error when lunched
ImportError: cannot import name 'ParameterSource' from 'click.core' (/usr/local/lib/python3.9/site-packages/click/core.py)```
can anyone help me with how to use it? i dont really understand the doc
ive installed it from github using terminal
๐ Bug Report
To Reproduce
Environment
__Originally posted by @erney83 in https://github.com/facebook/flipper/issues/3764__
__Originally posted by @erney83 in https://github.com/narrowcast/facebook-ads-api/issues/71__
__Originally posted by @erney83 in https://github.com/narrowcast/facebook-ads-api/issues/72__
__Originally posted by @erney83 in https://github.com/facebook/flipper/issues/3801__
try black [filename].py
Describe the bug
If a line that exceeds the character limit has parameter comments, the function won't be moved to a new line inside parentheses.
Without parameter comments, Black will move the function inside parentheses.
Black should be consistent with these cases.
To Reproduce
For example, take this code:
long_variable_name = long_function_name(
arg1,
# comment
arg2,
)
long_variable_name = (
long_function_name(
arg1,
...
no way to set it as default formatter?
for python only
thank you
Is this expected?
def benchmark(function=None, **kwargs):
if kwargs:
def _inner_decorator(function):
_benchmark(function, **kwargs)
return _inner_decorator
if function is not None:
_benchmark(function)
else:
raise TypeError("benchmark requires a function to benchmark")
Referring to the blank line after the if statement
Black seems to be enforcing it
expected, but subject to change: psf/black#3089
Thanks!
Please add the skip_new label to this PR
Description
Removed the hard coded SOURCE list from test_format.py. Now, black is run as part of the Lint CI and looks for sources automatically.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Thanks for submitting! I'm all for removing the hard-coded list ๐
Another option would be to just use black directly in the CI, since pre-commit does the check locally. So having it in Tox would be a bit redundant. Thoughts?
Hello ! I'm facing an issue while trying to use black to lint a file.
When trying to lint my piece of code (either with pre-commit or running black itself), the below error happen. Unfortunately, i can't provide any example as it's not my property.
The resulting error is:
error: cannot format core/nomenclature/tests.py: INTERNAL ERROR: Black produced code that is not equivalent to the source. Please report a bug on https://github.com/psf/black/issues. This diff might be helpful...
Description
This is one possible fix for: https://github.com/psf/black/issues/3040
I have added the --project-root command line argument which can be used to force black to evaluate paths relative to that root. Otherwise, black will pick up things like .git folders in submodules and use the submodule path as the project root instead.
We want to auto-format our code in Visual Studio Code but want to exclude 3rd-party git submodules by specifying them in pyproject.toml. Thi...
+1 on making test_format dynamically walk src + tests directories (and statically add setup.py) for python source files to test formatting on and continue to do it in parallel test_format tests if possible please. I feel it should be.
"Any color you like" is a reference to Henry Ford
Describe the bug
Black's --preview mode produces invalid code in the first pass, causing second pass to fail.
To Reproduce
For example, take this code:
some_dict = {
"something_something":
r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",
}
And run it with these arguments:
$ black --preview file.py
The resulting error is:
error...
Description
It's easier to update all of them at once.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Hmm I thought black had support for some kind of fluid call structure? re. https://github.com/psf/black/issues/3100
I can't remember what it looks like though.
myst-parser likes to pin sphinx hence the combined PR
I still haven't looked into the test infrastructure improvements, but everything else looks great! I'm so sorry I took so long to review this, thank you so much for waiting!
We have 31 open pull requests ๐
Either way, I'm probably done for the night. I still have a lot of things to pick up, but at least I have a start now ๐
Can't wait until this goes down again ๐
4bb7bf2 Remove newline after code block open (#3035) - saroad2
The docs build passed, so it's a ๐ from me! ๐
Once it doesn't fit on the line, yeah
Ah that explains it.
Thanks for clarifying!
some_dict = {
"something_something":
r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",
}
Under preview, what should this be mapped to?
I think the issue is related to the fact that r-strings aren't merged with StringMerger
Then I think StringParenWrapper makes a mistake
ichard action spamming my inbox ๐
I also think we don't need a redundant second run of black on itself ...
Haha, I found a little bit of free time
Description
Added a new feature in preview mode: Black now knows how to trim trailing whitespaces inside f-strings.
For example the following code:
``python
print(f"there are { 2 } unnecessary spaces in this f string")
print(f"there are { 3} unnecessary spaces on the left")
print(f"there are {3 } unnecessary spaces on the right")
print(f"you should trim { 'me' } and { 'me!' }")
print(f"trimming is easy as { 1 + 1 } == {2}")
will transform to:
```python
pr...
re #3119 above, I don't know if we should accept partial solutions like this. I fully get that a majority of fstrings only have trivial expressions (names or attributes) in them, but i'm not entirely sure the added complexity is worth the benefit
@errant barn - Are we missing something on https://github.com/psf/black/pull/3114 - This is definitely causing redundancy right?
Or am I missing something
Yeah, it's definitely redundant. They have a point that it shouldn't probably be in the test suite though
Currently the redundancy is local, since we have a pre-commit hook and we also test it. Moving it to tox wouldn't help, so if we wanted to get rid of it, we could let pre-commit handle local development and have a CI check dedicated to black
Oh is his most recent point true, that even our dev pre-commit runs with the latest released version? In that case the redundancy would be justified
And I'm somewhat ambivalent about this. It's convenient to have it in the test suite, but perhaps not the most elegant thing. Getting rid of the hard coded list makes it better by a mile either way though
I'd like to close https://github.com/psf/black/issues/333
- I don't see Black ever gaining support
- There are other tools that already do a great job (isort and usort come to mind)
big +1
Yeah Iโm all for that with a pathlib iterdir + deny list if needed
Ya. This isnโt for us. Letโs just link isort and usort
Both are way slower so I donโt want that slowness in black
Since isort 5 got released with proper black support, there really isn't a good argument to support optimizing imports in Black
and now there's also usort
The state of things is a lot better than it was back when the issue was made.
Once isort 5.11 is released, the only discrepancy I'm aware of - magic trailing commas - will be properly supported as well.
๐
on a related note, fastero is pretty cool; gotta remember to use it instead of timeit
This how you profiled?
Nah I used py-spy for profiling
It is false-ish
.pre-commit-config.yaml lines 7 to 13
- id: black
name: black
language: system
entry: black
minimum_pre_commit_version: 2.9.2
require_serial: true
types_or: [python, pyi]```
we run black over the project as a system hook, so effectively we're just running black as a shell command
now if the black command doesn't point to the dev version of black, then it'll probably use the pypi version that's available somewhere on the system
for CI, we install the dev / currently being tested revision of black before running pre-commit
.github/workflows/lint.yml lines 22 to 28
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install -e '.[d]'
- name: Lint
uses: pre-commit/action@v3.0.0```
not sure why we install with the [d] extra to be honest, but we are using the development version
+1
Description
Updates and closes https://github.com/psf/black/pull/3120:
The new https://github.com/actions/setup-python/releases/tag/v4.0.0 now requires setting a Python version via python-version: or python-version-file:.
Let's use python-version: "*", already used for one of the workflows:
Checklist - did you ...
- [n/a] Add a CHANGE...
sussy baka
Hi Team! May I have a pointer to whatโs the difference between black and black[jupyter]? I searched in Black Repo and documentation. It seems that black[jupyter] adds extension based on Black to support formatting Jupyter notebooks. Iโm curious if there are any features in vanilla black but not in black[jupyter]? Thanks a lot!
just formatting notebooks! And [jupyter] isn't anything special, if you've installed ipython elsewhere that'll do!
Thanks!
@JelleZijlstra What do you prefer here?
Current output of black:
self.assertEqual(
[
[tuple(call) for call in super_mail.call_args_list],
(
"",
(),
dict(
description="((a descriptive description)) #expected-title-tag",
tags={
"ORIGxNAL_AUTHOR": "expected-user",
"TOOL": "//expected/tool",
},
revi...
I just want to share with the black team that all roughly 40 different python containers we run at my job are now entirely scrubbed by black and it is a pre-commit hook now too. We used to have little tiffs over standards and personal preferences, but having an outside decision maker helped us a ton by removing any agency on the matter. We just set the line length limit to 120 and forced to keep trailing commas in pyproject.toml files, which is also great, because now that we have the pyproject.toml standardized we've started to standardize our pytest env on that too.
So thanks for the work.
thanks for the feedback, it's great to read success stories like this ๐
sorry, but how are you measuring time that precisely?
is that pico seconds?
Bonk on https://github.com/psf/black/pull/2525#issuecomment-1154716116 cc @bright glacier
nah just milli and microseconds
I used the fastero pypi package
Thanks for sticking with this, lets just try explain all things and answers peoples main points in responses moving forward and I feel we can down the on PR miscommunication.
https://github.com/psf/black/runs/6884433369?check_suite_focus=true - Can someone help me workout what this diff-shades error means
Error: Invalid value for 'analysis': File 'preview-changes-main-6c1bd08f16.json' does not exist.
Also, when we targeting next release. I've been slack here. Looking at our changes - i think it's well past time?
yes, we should do it soon
I'll take a look later today and get a PR up for the release and the someone can panic and say they want something merged first like always happens ๐
hmm I'm not sure if I agree with removing black from pre-commit
I guess from a purity standpoint, it's not great, but functionally it's mostly fine.
It's been a recurring problem, the latest release doesn't type check cleanly under mypyc and I didn't make the workflow robust enough to handle that.
It compiles black before testing it because it actually saves time. I can make it fall back to running black under interpreted if compilation fails if you'd like.
My main problem is that if contributors don't run tests (and even if they do so, they have to run a special test environment), then they won't know their code changes aren't black compliant until CI runs the lint job. That introduces a cycle which is annoying.
pre-commit for this situation is far from perfect as it doesn't always pick up the dev version of Black (usually when you don't activate a virtual environment) when checking the project, but IMO it's better than not having it.
I'm OK with moving the self-check outside of the test suite, but assuming we can work around pre-commit's flaws, then I'd suggest keeping black in pre-commit.
Pretty sure we could disable the black hook in lint CI if we so wanted.
Or how can we help with the compilation problem here? Should we open an issue?
My main goal is not wasting CI and local dev time running it twice. I already dislike we have to run pre-commit and tox seperately anyways - But that seems to be the python standard CI way these days ...
I also fine running the stable version will cause confusion and pain if we have formatting changes locally but the stable version does not - This will happen in next release we move preview changes onto main by default in late December
I also personally don't have the energy to debate, so if people want it back, feel free to restore it. I just find it wasteful, potentially causing confusion and we don't get pre-commit running on our differnet supported environments.
Ideally it would be nice to have pre-commit to install black from the local commit.
Hi, sorry but this channel is for Black development, try the #help category!
ok
?
Hi, sorry but this channel is for Black development, try the #help category!
psf/black#3111 makes no sense to me.
I'll check the sdist for a few of the reported versions, but according to the tags, ParameterSource should exist ยฏ_(ใ)_/ยฏ
I wonder if a redistributor of click messed up
hm yeah click.core.ParameterSource has been a valid name since click 8.0
I assumed it would be ubuntu or debian but I couldn't reproduce in a ubuntu VM or in a ubuntu docker image
And the debian package worked fine in a virtual environment
Perhaps it could be something like conda causing two different versions to be installed and whichever python install is running black is using the wrong version
Ubuntu seems to have 5 python-click packages, 3 of which are out of date so Ubuntu isn't entirely ruled out
Ubuntu's package management system scares me ๐
Oh interestingly, all of them are out of date. It's just that 3 of them have versions < 8.0 the other two are 8.0.3
I discoverd an different beheavior between "change" and "check":
If I run "black" to my project, it reports no changes.
$ black --diff *.py
All done! โจ ๐ฐ โจ
12 files would be left unchanged.
But "--check" reports an issue
$ black --check --preview --diff *.py
--- get_curve.py 2022-06-17 07:38:10.719823 +0000
+++ get_curve.py 2022-06-17 07:39:26.411995 +0000
@@ -31,11 +31,12 @@
sens_data, sens_ext_datal, sens_owm_data, t1, t2, t3 = extract_pg_data(
...
PEP 621 provides project.requires-python field in pyproject.toml. I expect, that most of the tools will support this field eventually.
Each code-related linter and formatter has a setting for supported python version.
Using this field would be good for tool interoperability in the future.
Related: https://github.com/psf/black/issues/751#issuecomment-778441893
What's the reason black splits strings that are too long at the end of a word and moving the white space to the start of the new line?
Don't remember if it was an explicit decision, but I think this way it's easier to verify the spaces are there
Description
This is a quick follow up from psf/requests#6140. This PR fixes the dead link by moving it to https://requests.readthedocs.io/en/latest/ which will be the primary domain for the project going forward.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
I was confused at first how requests is connected to the Black project, I forgot we had a testimonial :)
Thank you!
Describe the bug
Black currently inserts an empty line before functions when they are defined inside a block.
I don't want that to happen if a function is the first thing defined in a block, so I try to add a skip (see also #3089).
I get an error as a result:
INTERNAL ERROR: Black produced different code on the second pass of the formatter.
To Reproduce
def func():
try:
if True :# fmt: skip
async def another_func():
pass...
i wish
Black v22.3.0
Options
--line-length=88
--safe
Input
f = None
for i in range(5):
with open("app.log", "w") as f:
if...
Description
The following code fails:
# -*- coding: utf-8 -*-
setup(
entry_points={
# fmt: off
"console_scripts": [
"foo-bar"
"=foo.bar.:main",
# fmt: on
]
},
)
The following code works:
# -*- coding: utf-8 -*-
setup(
entry_points={
# fmt: off
"console_scripts": [
"foo-bar"
"=foo.bar.:main",
]
# fmt: on
},
)
`...
For golang projects, the formatter can reorder import statements, which makes the code look cleaner.
For C++ projects, the code style also contains guidance on the order of include statements.
That being the case, why doesn't black consider reordering the Import statements?
Two questions:
- is there a reason other than character length per line that black decides to put quotes in own lines? (see picture)
- if I have
max-line-lengthset in my.flake8, does black consider it? Or should the line adjustment be made to some other config file?
black doesn't look at .flake8, it has its own config file
The docs on line length aren't exactly clear on this https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-length
not sure what you mean by (1), I don't see quotes on its own line
Yup, presumably when it's collapsed it violates the line length limit hence why it's split.
The github readme mentions reading opts from pyproject.toml. Should I use that, or own config file that was mentioned above?
that's the file I meant
Jelle was unclear, Black only looks at pyproject.toml by default
I never misspeak ๐
Or make typos.
Alright, seems like [tool.black] is the key
Thank you
Confirming that it was the line length
Excuse me for bothering further, is there a verbose option when running black via the CLI or otherwise, where each change is explained with the reasoning and which black rule it met for the adjustment?
no, Black doesn't really separate out its changes
and it doesn't have a concept of "rules" even internally
rather most of the complexity is in a big algorithm for how to fit the code within the line length
Ah, I intuitively thought it was some sort of a priority-based rule engine. My fault for not digging into the sources. Thank you regardless
for completeness, there is a verbose mode, but it mostly prints info about where it finds the config and what files it looks at
Has anyone run into this? - Currently running black v20.8b0 in my environment and running into issue when running pip install I hit the following error
Collecting black==20.8b0
Using cached https://nexus.jx.cicd/black-20.8b0.tar.gz (1.1 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error
ร Preparing metadata (pyproject.toml) did not run successfully.
โ exit code: 1
โฐโ> [51 lines of output]
Traceback (most recent call last):
File "/private/var/folders/0t/f4fb584j0d9d7bb4g6f05vy40000gp/T/pip-build-env-pbooiros/overlay/lib/python3.7/site-packages/setuptools_scm/_entrypoints.py", line 72, in <module>
from importlib.metadata import entry_points # type: ignore
ModuleNotFoundError: No module named 'importlib.metadata'
It just started happening today
If I upgrade the version to one of the latest versions of black I dont see the issue pop up anymore
I wonder if the latest setuptools-scm release broke things, again.
@bright glacier I think you maybe right, I see new versions of setuptools-scm
Preparing metadata (pyproject.toml) ... done
can't reproduce on Python 3.7 with black==20.8b0
if you uninstall black and importlib.metadata manually then install black, I was able to reproduce
which ones? the ones from this and last year should work fine because wheels exist for them so there's no build step involved where setuptools-scm could crash while installing.
That's odd since pip's build isolation should mean this shouldn't affect the build ...
black==20.8b0 upgrade ==> 21.12b0
I couldnt go to latest because of conflicts with click but this is two versions back
yeah we have wheels available for 21.12b0 so that does eliminate setuptool-scm entirely
@bright glacier thanks for the help on this, I'll test more on the setuptool-scm recent release but I think we'll just stick with the newest version (21.12b0)
I still can't reproduce the issue even if I uninstall importlib.metadata before install black==20.8b0
what is your pip version?
pip 22.1.2
@bright glacier could this possible be the issue that we were talking about
importlibs with python 3.8 or higher
When using setuptools_scm in a CI pipeline to install a package I'm getting: ModuleNotFoundError: No module named 'importlib.metadata' compare https://github.com/audeering/a...
It was an issue with setuptools-scm. I chatted with the setuptools-scm maintainer and they confirmed.
Thanks @bright glacier on the follow up, I found the following solution to work.
- black v21.8b0 - Pin setuptools-scm build-time dependency version (#2457) due to setuptools-scm breaking changes.
https://github.com/psf/black/pull/2457/files#diff-50c86b7ed8ac2cf95bd48334961bf0530cdc77b5a56f852c5c61b89d735fd711 - Upgrading to black 21.12b0 takes care of this issue completely
Ah that's good to know, thanks for investigating further!
If you encounter other packaging weirdness (well except for poetry or PDM, those aren't PyPA projects), just know discord.gg/pypa exists
If it's related to Black, obviously ask here first, but just in case it comes in helpful ^^
thanks for sending this, I'll join this, I like finding weirdness in code and tracing its source
I'm going to see if I can work on the release CI situation to hopefully unblock a new release
I'd appreciate it if someone could go through the commit log / changelog and make sure any code style changes have been (sufficiently) documented in the (future) Black Code Style documentation