#black-formatter
1 messages Β· Page 33 of 1
basically websites. I can't share the more recent as it has private information but I was proud of the result.
the second latest would be https://ichard26.github.io which still has no real content yet :p
Richard Si (ichard26)'s personal place for writings all about FOSS and Python.
As much as people hate on CSS, I haven't endured much pain from it yet π although to be fair I'm working on small sites that don't even need multiple stylesheets
Nice π
3800ebd Avoid magic-trailing-comma in single-element su... - jpy-git
I recently accidentally cleared out all of my pre-commit hook installations and discovered using the latest version of everything nets us some new warnings:
β― pre-commit run -a
black....................................................................Passed
Check pre-commit rev in example..........................................Passed
Check black version in the basics example................................Passed
flake8.................................................................
will check tomorrow
!remind 18H Don't forget to clear out some pending reviews once the diff-shades integration is useful again!!!
Your reminder will arrive on <t:1648153448:F>!
hmm I might be in a meeting at that time, but it should be over soon after so it's probably fine.
Description
Closes #2949. Fixes a couple places where we were using the same variable name as we are iterating over.
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
14e5ce5 Remove unnecessary parentheses from tuple unpac... - jpy-git
Thanks! This will unblock #2891 :)
14d84ba Resolve new flake8-bugbear errors (B020) (GH-2950) - jpy-git
Description
Now PRs will run two diff-shades jobs, "preview-changes" which formats all projects with preview=True, and "assert-no-changes" which formats all projects with preview=False. The latter also fails if any changes were made.
Also the workflow_dispatch feature was dropped since it was complicating everything for little gain.
Example run: https://github.com/ichard26/black/pull/15
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- ...
For separating the test cases between preview and stable, there's two main ways we could do it:
- Keep them in separate files (affixed with some kind of marker / stored in a specific directory)
- Enhance the current test data format so an expected result can be defined for either (or both) modes
The latter would keep duplication down, but would be less flexible overall. Although to be fair it's not like we'd be forced to choose only one. We could implement both. I just want to document the general process.
I like the second idea, maybe add a separate # preview-output section
Me too, all for reducing duplication
Here's your reminder: Don't forget to clear out some pending reviews once the diff-shades integration is useful again!!!
[Jump back to when you created the reminder](#black-formatter message)
I guess I'll review the currently open PRs now and then I can look into improving our testing infrastructure after
Describe the bug
Under preview, the removal of unnecessary parenthesizes can be unstable if there's multiple -- each pass removes only one pair.
To Reproduce
For example, take this code:
for (x, y) in enumerate(range(10)):
pass
And run it with these arguments:
$ black file.py --preview
The resulting error is:
error: cannot format test.py: INTERNAL ERROR: Black produced different code on the second pass of the format...
Removing multiple unnecessary parenthesizes for for assignment targes is unstable #2952
ah whatever, the typo can live on
It's this kind of instability I'm worried about with stuff like this
This case is unstable unfortunately:
with (((open("test"))) as a):
pass
Mode(target_versions={, , }, line_length=88, string_normalization=True, is_pyi=False, is_ipynb=False, magic_trailing_comma=True, experimental_string_processing=False, python_cell_magics=set(), preview=True)
--- source
+++ first pass
@@ -1,2 +1,2 @@
-with (((open("test"))) as a):
+with ((open("test"))) as a:
pass
--- first pass
+++ second pass
@@ -1,2 +1,2 @@
-with ((open(...
I won't comment on the actual formatting style, but I got quite a few other suggestions. Not sure if this is too minor, but I'd recommend checking this is covered in the Black code style documentation!
Thanks again!
Finding lots of bugs in my reviews today 
good catch! I was worried about that sort of thing in my reviews but didn't look hard enough
I feel a bit uneasy merging formatting changes without a fully operational diff-shades integration, but this looks fine to me :slightly_smiling_face:
Thanks again for all of your work!
if the PR above has a bug, it'd be on me with how thorough I'm trying to be π
!remind 3H finish off some more reviews
Your reminder will arrive on <t:1648173267:F>!
Description
Investigating #2952. Really weird but I'm not seeing this issue and this unit test works fine for me π
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
I wonder how many non magic trailing comma instability bugs we're potentially hiding with the second pass hack
I am setting default formatter to be black formatter
How to specify that? Thank you
you're missing a comma :p
lemme pull out my vscode config file and see what the right value is
I dont know why "[python]" is still orange
"[python]": {
"editor.defaultFormatter": "ms-python.python"
},
this is what I have
are you missing a comma on line 7 above
put a comma at the end of line 7
Sorry got it
Do I need to click "save" or anything to take effect?
I can't see any changes when I push shift + alt + f
did you set
"python.formatting.provider": "black",
too?
it needs to be outside of the python block, i.e. in the main configuration scope
πΊ lovely!
Here's your reminder: finish off some more reviews
[Jump back to when you created the reminder](#black-formatter message)
(replying to @bright glacier here, since it seems more topical than #unit-testing )
Black no longer crashes on parenthesised context managers, but it doesn't add parens when needed - even if I specify -t py39 or py310. See eg
https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AHRAK5dAD2IimZxl1N_Wg0-BAclsm6AXNYZqFDXdkKKtCkCz8fX-xEYu0zyMr0UnfF3cCKW4WPbUzY_SKtXxPCEVnsSqmPTCseINvICJiA4wa-ldoG94oFLw5QLkhuSPUbE5T9V5MKsv_YeT2anIazy9fx0vYdDMgP7wrueuEOoN7VlkkuODYIdaPA0rvUajAO_7G49LXyDn3uRuxsdN_lCE6LsITgGVfotiSdZKmXAtNonIAAAAHUbwYesYXDYAAHKAdIDAAD0D13AscRn-wIAAAAABFla
and https://github.com/psf/black/issues/664
Describe the style change
Black indents items in brackets to help fit more on the screen, however in some cases, one can now see 2 less lines of code, as a tradeoff for seeing 2 more characters. This extra whitespace, along with making the code more verbose could be undesirable. Maybe a sensible default should be chosen that unless the win of pulling the line left is less than x chars, then rather leave it as is. E.g. maybe the minimum win should be 4 chars.
**Examples in the curren...
@JelleZijlstra @ichard26 I've fixed both for and with bracket removals to work in one pass now π
Is that a preferred way for you guys to breakdown list comprehension into multiple lines?
Yeah
I want to keep it remain single line, can I change the setting?
You can change line length limits, but I'd maybe just move the comment
I see. Thank you
ππΏ
I forgot to mark my review as "request changes" which is relevant since this PR can still crash.
yeaahh I misread the room 
It's a bit tricky with how it was an undocumented feature, but IIRC I had a idea to make it work. It just involves making it special as usual with hacks :p
hey richard, i accidentally edited the duration of this reminder. you need it to remind you april 23?
can you do !remind list, i just want to make sure that i did indeed edit your reminder
Yea that was the intention, but honestly it's more of a general reminder for "sometime in the future"
!remind list
Reminder #4276: expires <t:1648252693:R> (ID: 4276)
is the github .git-blame-ignore-rev blame support out of beta? don't forget to attribute https://github.com/henrikhorluck
Reminder #4206: expires <t:1651276650:R> (ID: 4206)
can we test CPython 3.11-dev on GHA yet?
ok you can !remind edit duration 4276 1m
!remind edit duration 4276 1m
That reminder has been edited successfully!
sry :) i'll be more careful haha
no worries!
I do love a good hack! Sadly most of my best in Hypothesis are so cursed that I don't want to tell people about them for fear of inspiring others π
how do i comment out a certain area of text from black formatting?
surround it with # fmt: off and # fmt: on -- note they have to be on the same level of indention
you might be able to try # fmt: skip but it's rather buggy right now
looks like f-string time
is this a graphQL query? they are always a pain to write out :)
My solution when I last dealt with graphQL was to add placeholder values and use str.replace on 'em -- not exactly pretty 
possibly one of the few cases where string.Template could be an alright solution (https://docs.python.org/3.10/library/string.html#template-strings)
I forgot string.Template was a thing π
Ok cool
thank you
I can't wait to use it
so I don't need to use my hackyish
function anymore
Describe the style change
Black should merge split strings that fit into a single line.
Examples in the current Black style
def f():
raise ValueError("This was previously formatted " "with a smaller line-length")
Desired style
def f():
raise ValueError("This was previously formatted with a smaller line-length")
Additional context
In some projects, we have started with line-length of 80 and now we're increasin...
Is your feature request related to a problem? Please describe.
I've just learned that this
a = 1_2_3_4_5.6_7_8_9
is a valid alternative way of writing
a = 12345.6789
I think the intention is to let people break up large numbers if they want i.e. 1_000_000 instead of 1000000
Describe the solution you'd like
Should we decide on a consistent format for black and remove these underscores?
Describe alternatives you've considered
...
Is your feature request related to a problem? Please describe.
At the moment black doesn't seem to have any strong opinions on brackets around lambda expressions in functions.
Describe the solution you'd like
I had a couple initial thoughts:
A) Remove brackets if it's used as a positional argument
i.e.
map((lambda n: n**2), [1, 2, 3, 4, 5])
becomes
map(lambda n: n**2, [1, 2, 3, 4, 5])
B) require brackets as used as a keyword argument (o...
!remind 5H do a systematic review of the current code style and make sure the docs are up to date
Your reminder will arrive on <t:1648329582:F>!
My wifi connection is awful on my main machine and I don't know why... loading any GitHub page is unreliable :/
well -- at least I can still access the web lol
fun fun fun, 2.4GHz works but tops out @ 2 Mbps while 5GHz doesn't work at all (pictured below)
Do we have an issue about taking advantage of parenthesized with @dense jungle ?
I thought we did, but I can't find one hmmm
Not sure, can take a look
hmmm I remember we added a section to the future style docs with a better style, I guess whatever issue had that shared around would be it
Here's your reminder: do a systematic review of the current code style and make sure the docs are up to date
[Jump back to when you created the reminder](#black-formatter message)
turned on this option so we can update branches and get more diff-shades goodness π
Seems like it's new in #2174 (your big docs rewrite)
it goes way back to March 2020 https://github.com/psf/black/issues/664#issuecomment-594771153
I forgot we also agreed to use backslashes π
hm did we actually commit it? I checked out the commit before your PR but don't see it
yeah let's not
Since we have a nicer option in 3.9+
oh the rest of the section was from somewhere else, but it looks like you added the sentence "Although when the target version is Python 3.9 or higher, Black will use parentheses instead since theyβre allowed in Python 3.9 and higher."
That sounds about right but I can barely remember :)
Can we get away marking parenthesized with as a 3.9 feature? It could break code using any implementation that isn't CPython or PyPy, but then again it's only those two that are used in practice
Yes, I think it's fine
I'm fine with it too. Wish it was made official but oh well π
I took care of the cleanup. This is good to land now!
Describe the bug
On Centos 7:
WARNING: You are using pip version 21.2.3; however, version 22.0.4 is available.
$ python3.9 -m venv venv
$ source venv/bin/activate.csh
(venv) $ python3 -m pip install black
(venv) $ black --version
black, 22.1.0 (compiled: yes)
(venv) $ black . --check --diff --color
Traceback (most recent call last):
File "~/venv/bin/black", line 8, in
sys.exit(patched_main())
File "src/black/__init__.py", line 1423, in patched_main
File "...
Describe the bug
The Github Action step:
- name: Run black
uses: psf/black@stable
with:
options: "--check --diff"
version: "22.1.0"
fails with the following trackeback:
Traceback (most recent call last):
File "/home/runner/work/_actions/psf/black/stable/.black-env/bin/black", line 8, in
sys.exit(patched_main())
File "src/black/__init__.py", line 1423, in patched_main
File "src/black/__init__.py", line 1[40](https://github.com/st...
This is pretty bad, would appreciate contributions addressing this
the fun moment when you write a message to report a bug and then 2 issues get opened before you can send
Either pinning click or making us not use _unicodefun
We should be able to do a release today to deploy the fix
Hello everyone, I am trying to use black but I am fairly new with this tool. I wanted to ask help here instead of opening a ticket.
I have a project running under python 3.9 inside an venv (called .env). I have installed black under this venv with the pip command as instructed in the get started.
When I launch black i get the following output:
black
Traceback (most recent call last):
File "/Users/.../myProject/.env/bin/black", line 8, in <module>
sys.exit(patched_main())
File "src/black/__init__.py", line 1423, in patched_main
File "src/black/__init__.py", line 1409, in patch_click
ImportError: cannot import name '_unicodefun' from 'click' (/Users/.../myProject/.env/lib/python3.9/site-packages/click/__init__.py)
Any idea of what's missing? Also, I am running on macOS if it can help the troubleshooting
do pip install click==8.0.4
Thanks @frozen badge , actually I have 8.1.0 installed, would it be the source of my issue?
yes
they removed something that black uses in the 8.1.0 release which was like 30 minutes ago
ah ah ah, i started to use black at quite the wrong moment π
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
very unlucky lol π
that's me π
same happened to a friend of mine which is why im here 
Is there any open ticket that i can follow about this issue?
I didnβt found anything earlier when i tried to search for one...or maybe i missed it π€
Thanks a million @frozen badge
thanks for the quick PR @bright glacier ! fyi you can edit the changelog from the web UI at https://github.com/psf/black/blob/ichard26-patch-1/CHANGES.md
(or press . in the repo which should open github.dev/vscode web )
hm, something still wrong with the mypyc build in https://github.com/psf/black/runs/5725257122?check_suite_focus=true
OK, so let's get a release out ASAP. We'll just ignore mypyc and we can do a follow up point release with compiled wheels later.
Unless we want to drop 3.6 like right now which seems untenable..?
I assume 8.1.0 dropped other stuff from the API that we were using? hence mypyc freaking out
hm, seems bad to have a release without wheels
why isn't that build using click<8.1.0?
it's just a speed up, we'll still have the pure python one obviously
oh hmm, yeah
did I mess up the syntax?
oh right, the workflow installs click as it's a dependency of the helper script and that's still unbounded
I'm going to try removing the patch entirely as some people on GH were suggesting
I think when I get back to my main machine I'll set up some CI on another repo that tests out the development versions of our dependencies
this blew up way more than I expected
We could also just fix the patch code as it was catching the wrong exception apparently
Also I now realize click 8.1.0 dropping 3.6 is not a problem as we still support the older 8.x.x versions.. ah the joys of stress
think we do still need the patch ```% LANG=C python -m black src/black/init.py
,,,
RuntimeError: Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps.
This system lists some UTF-8 supporting locales that you can pick from. The following suitable locales were discovered: af_ZA.UTF-8, am_ET.UTF-8, be_BY.UTF-8, bg_BG.UTF-8, ca_ES.UTF-8, cs_CZ.UTF-8, da_DK.UTF-8, de_AT.UTF-8, de_CH.UTF-8, de_DE.UTF-8, el_GR.UTF-8, en_AU.UTF-8, en_CA.UTF-8, en_GB.UTF-8, en_IE.UTF-8, en_NZ.UTF-8, en_US.UTF-8, es_ES.UTF-8, et_EE.UTF-8, eu_ES.UTF-8, fi_FI.UTF-8, fr_BE.UTF-8, fr_CA.UTF-8, fr_CH.UTF-8, fr_FR.UTF-8, he_IL.UTF-8, hr_HR.UTF-8, hu_HU.UTF-8, hy_AM.UTF-8, is_IS.UTF-8, it_CH.UTF-8, it_IT.UTF-8, ja_JP.UTF-8, kk_KZ.UTF-8, ko_KR.UTF-8, lt_LT.UTF-8, nl_BE.UTF-8, nl_NL.UTF-8, no_NO.UTF-8, pl_PL.UTF-8, pt_BR.UTF-8, pt_PT.UTF-8, ro_RO.UTF-8, ru_RU.UTF-8, sk_SK.UTF-8, sl_SI.UTF-8, sr_YU.UTF-8, sv_SE.UTF-8, tr_TR.UTF-8, uk_UA.UTF-8, zh_CN.UTF-8, zh_HK.UTF-8, zh_TW.UTF-8
Yeah having black refuse to work sounds untenable even if it's only on 3.6
Fixes #2964
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
^ this works locally
click, not black but thanks!
lol oops
Description
The _unicodefun module has been removed from the click library.
In addition, it is also not actively being used in the black repository.
See reports here:
β’ https://github.com/pallets/click/issues/2225
β’ https://github.com/pallets/click/issues/2198
Checklist - did you ...
- [ n/a ] Add a CHANGELOG entry if necessary?
- [ n/a ] Add / update tests if necessary?
- [ n/a ] Add new / update outdated documentation?
this is still broken https://github.com/psf/black/runs/5725593238?check_suite_focus=true
Looks like it could be a bug in Click's typings
@bright glacier could we pin to <8.1.0 just for the mypyc build?
it's because it installs click early without the bound: https://github.com/psf/black/blob/ac7402cbf6a0deb5c74e9abcffc5bd7b1148fda5/.github/workflows/diff_shades.yml#L59-L67
.github/workflows/diff_shades.yml lines 59 to 67
- name: Install diff-shades and support dependencies
run: |
python -m pip install https://github.com/ichard26/diff-shades/archive/stable.zip
python -m pip install click packaging urllib3
python -m pip install -r .github/mypyc-requirements.txt
# After checking out old revisions, this might not exist so we'll use a copy.
cat scripts/diff_shades_gha_helper.py > helper.py
git config user.name "diff-shades-gha"
git config user.email "diff-shades-gha@example.com"```
yes, just pushed a commit to pin there π
diff-shades is building fine on my PR now too. Shall we wait for CI to pass on it, merge it, and release 21.3.0?
um 22.3.0
Everything feels super rushed, but I don't see what could go wrong if we leave off publishing the mypyc wheels
Any reason not to publish the wheels too?
those wheels are still the most unreliable part of the release process
We were overdue for a release anyway π
No? They're just slow to build, like an hour or so
and you still have to manually run some script for it, right?
It's still manual, yes but I trust mypyc enough where I can probably skip the manual testing so it's basically just "fire the workflow, wait 30 minutes, download the wheels and use twine to push 'em"
after all we've been using it in the diff-shades workflow for a while now
OK, let's just do that for this release too then
I've been meaning to upstream the mypyc wheel build workflow, but clearly I haven't gotten to it yet 
the list of linked issues on https://github.com/psf/black/issues/2964 is scary
OK so after calming down and figuring out what is even happening the plan is to essentially:
- merge psf/black#2966
- go through the release process for black 22.3.0
- release it
- and at the same time also build the mypyc wheels
do we want to wait to release everything at once or upload the wheels later once they're done?
Right. I can do steps 1-3. I think the wheels can be added later
Given the amount of breakage the faster we release the better
I agree.
will prepare the release PR noow
52 thumbs up π
OK I'll fire the mypyc build workflow now
gosh the overthinking part of me is now worrying that the fix doesn't work, ahhhhh
that would be embarrassing
Describe the bug
It looks like black is depending on click>=1.8.0, However, click changed the API in the new version 1.8.4, which is causing imports problems. BTW the pre-commit hook is also not working using the latest, stable version. I'm not sure if I'm the only one getting this!
To Reproduce
Just try to run black
The resulting error is:
File "src/black/__init__.py", line 1409, in patch_click
ImportError: cannot import name '_unicodefun' from 'cli...
time to eat lunch
time to actually drink my french vanilla, I didn't drink it because I was too focused on this madness :p
why :/
I'll push the other ones I have right now, but this is annoying and odd. Seems like actions/create-artifact made a broken zip file?
Description
Hi, first time contributor here! This PR fixes #2917 . The issue was that fmt skip comments were being handled inconsistently. A formatted version of the comment (e.g. #fmt:skip -> # fmt:skip in comment.value) was being compared to the original comment in the code (e.g. #fmt:skip in leaf.prefix), which would always be False.
Please let me know if there's anything that needs to be changed. I left a comment below explaining one of the changes. Also, does this...
seems rather similar to https://github.com/psf/black/pull/2682/files
Psst, fully automatic release processes are great https://hypothesis.works/articles/continuous-releases/
The Hypothesis continuous release process If you watch the Hypothesis changelog, youβll notice the rate of releases sped up dramatically in 2017.
We released over a hundred different versions, sometimes multiple times a day.
This is all thanks to our continuous release process.
Weβve completely automated the process of releasing, so every pull ...
our releases are pretty automated too (apart from the mypyc stuff). I feel like releasing every change immediately would create a lot of noise for users, but it's an interesting model
I'm setting up a repo that runs black's test suite against the latest development version everyday and I'm hitting quite a few issues
at this point 4 of our dependencies have dropped 3.6 support, and the latest aiohttp also breaks our test suite which is just lovely
jeez that's a concerning amount of overrides https://github.com/ichard26/black-deps-ci/blob/4e25ac3dea340a956e35dab37b2ac5c4177c105e/generate.py#L9-L24
So in total 7 of our user/test dependencies don't support 3.6 anymore (also yeah once aiohttp 4.0.0 goes out of alpha our CI is blowing up)
and I didn't even include all of our test dependencies as pytest is the only one necessary to run the test suite
So thanks to the various dependency related fires we've had lately, I've created ichard26/black-deps-ci which runs Black's test suite using the latest development versions for most of our dependencies (exceptions being subdependencies and most of the test dependencies)
Turns out there's a lot of overrides necessary for CI to be green. Python 3.6 support being dropped is responsible for the vast majority of overrides, but on the other hand, aiohttp breaks our ...
I think https://github.com/pallets/click/issues/2227 is affecting us too, saw that same error in the mypyc output
well that's great 
Sure, but you still get disproportionate benefits from automating the last part of the process - anyone authorised can cut a release just by merging.
For smaller projects I just python setup.py sdist bdist_wheel && twine upload --skip-existing dist/* at the end of passing builds on main - it only releases if I've bumped the version number!
We need use GitHub releases tho as we upload binaries there that people use now ...
Something make me uneasy about a commit being able to cause all that uploading and potential mess with a few bugs
Still doable with github actions!
And you can use the CODEOWNERS file to restrict permissions appropriately.
whats going on everybody
Upgrade on library click https://pypi.org/project/click/8.1.0/ broken, I think we can solve restricting version of library to 8.0.4

ew setup.py sdist
pipx run build && pipx run twine upload --skip-existing dist/* plz
re: #2966 he could have had 21.10b0 pinned, just not click
ew, build-time dependencies π
?
@lament crow thanks for the support in telling people they have the wrong version of Black installed π
hah, sure
The change log does a poor job explaining what a "code cell separator" is to people who haven't heard it
try:
from aiohttp.test_utils import unittest_run_loop
except ImportError:
# unittest_run_loop is unnecessary and a no-op since aiohttp 3.8, and aiohttp 4
# removed it. To maintain compatiblity, we can make our own no-op decorator.
def unittest_run_loop(function: Callable[..., None]) -> Callable[..., None]:
return function
tests/test_blackd.py:22:5: error: All conditional function variants must have identical signatures
def unittest_run_loop(function: Callable[..., None]) -> Callable[..., None]:
not sure why mypy is erroring here hmm, especially as I can't even tell what other function variants exist
it's very particular about this
Is the first param named function in the unit test version?
like maybe the argument name is different
I was looking at an issue the other day where someone suggested mypy should tell you what the difference in the signature is
aiohttp/test_utils.py lines 487 to 498
def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any:
"""
A decorator dedicated to use with asynchronous AioHTTPTestCase test methods.
In 3.8+, this does nothing.
"""
warnings.warn(
"Decorator `β@unittest_run_loop`β is no longer needed in aiohttp 3.8+",
DeprecationWarning,
stacklevel=2,
)
return func```
and take *args and **kwargs
It'd be nice if mypy emitted the other signature variants but I guess that's too difficult
(although I'm still surprised how it's finding this signature as I don't think typeshed has aiohttp, and I have aiohttp 4 installed)
yes that's what the issue I referred to asked for π it should be possible
aiohttp is py.typed I think
β― pip list | grep "aiohttp"
aiohttp 4.0.0a1
unittest_run_loop doesn't exist since aiohttp 4
maybe mypy is looking at a different venv?
aiohttp/test_utils.py lines 453 to 466
def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any:
"""A decorator dedicated to use with asynchronous methods of an
AioHTTPTestCase.
Handles executing an asynchronous function, using
the self.loop of the AioHTTPTestCase.
"""
@functools.wraps(func, *args, **kwargs)
def new_func(self: Any, *inner_args: Any, **inner_kwargs: Any) -> Any:
return self.loop.run_until_complete(
func(self, *inner_args, **inner_kwargs))
return new_func```
turns out it was not even deprecated in 4.0.0a1 Β―_(γ)_/Β―
I guess they keep multiple active branches hence this situation..?
Description
aiohttp.test_utils.unittest_run_loop was deprecated since aiohttp 3.8 and aiohttp 4 (which isn't a thing quite yet) removes it. To maintain compatibility with the full range of versions we declare to support, test_blackd.py will now define a no-op replacement if it can't be imported.
Also, mypy is painfully slow to use without a cache, let's reenable it.
Resolves GH-2971.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- [x] Add / u...
<!--
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
A recent version of click has been released which removes _unicodefun, breaking black (see also https://github.com/dask/distributed/issues/6013).
To Reproduce
docker run --rm -it python:3.9-alpine sh
pip install "click==8.1.0" "black==22.1.0"
black .
The resulting error is:
Traceback (most recent call last):
File "/usr/local/bin/black", line 8, in
sys.exit(patched_main())
File "/usr/local/lib/python3.9/site-packages/...
Ugh
You would think that a project aimed at developers wouldn't get as many issues about something that has already been reported and fixed...
Hello. I have an issue using black formatter for my python code. I installed it and ran it: black main.py. But instead of formatting indentations it just crashes.
What's the message? And have you managed to narrow down the cause at all?
error: cannot format main.py: Cannot parse: 17:0: print("This country code was not found") All done! 1 file failed to reformat.
The problem was that print line had an indentation problem. I thought it should fix it to see if it works, but it crashed. I then fixed indentation myself and black returned: All done! β¨ π° β¨ 1 file left unchanged.
Ah, we can't really do much if the file is invalid Python
so it can only work for correct syntax?
Yep, since we rely on Python parsers to do the formatting in the first place
okay, thank you. And another question. I have installed black and use it in my local machine as a script in my package.json. But if I upload this project to github and someone will clone repo, will he be able to run script?
Hmm, I'm not that familiar with the machinery, but as long as they have your configuration (if any) and have installed Black, it should be fine!
Ordinarily you'd specify Black as some type of dev requirement for people to easily install everything they need
I did not configure my black , I used default configuration if it matters
Should be that much easier then
okay! Thank you so much!
You're most welcome!
A space is inserted between function calls and colons within list comprehensions.
To Reproduce
running black 22.3.0 (black file.py) on the following file
test[x:]
test[(x):]
test[len(x):]
test[len(y):len(x):]
produecs the following formatted file
test[x:]
test[(x):]
test[len(x) :]
test[len(y) : len(x) :]
Expected behavior
I would expect the file to remain unchanged.
Click 8.1.1 was released with a fix for pallets/click#2227.
https://github.com/psf/black/runs/5760994213?check_suite_focus=true hmm I guess mypyc just ignored that type ignore? that's fun
bah, I'm dumb, it's main that's still problematic
I think it's because it's building main
huh there is no #2980
Yay I can remove that override now :)
3dea6e3 Convert index.rst and license.rst to markdo... - gunungpw
Can confirm this unbreaks mypyc locally with click==8.1.1 π
Description
Two month ago, #2744 introduced a way to support formatting of jupyter cells with custom python cell magics.
In the current FAQ it is mentioned that this would not be possible: https://black.readthedocs.io/en/latest/faq.html#why-is-my-jupyter-notebook-cell-not-formatted
Therefore I updated the FAQ and mentioned the new black --python-cell-magics writeline hello.ipynb syntax.
I've also tested this locally:
https://user-images.githubusercontent.com/44469195/16099079...
hi all! I just discovered that black defaults to an 88 char line length, while PEP8 specifies 79. Why does black allow a longer line length?
Nice - apologies for having forgotten about updating the FAQ in the other PR
79 is insanely short
Even 88 is short imho, i use 100
I thought that was the point of the standard - to standardise and remove opinions
The reasoning is covered in the docs https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-length
I missed that, thanks!
Just read it - does not really explain why black decided to break with PEP8 rather than trying to change PEP8
Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters
<pep8.org>
(Although it does then say "comments and docstrings should still be 72 chars")
My point is that 88 should not be the default, PEP8 should be the default. If teams want to go bigger that's up to them
I expect I am not alone in assuming that a PSF project would follow PSF standards out of the box
PEP8 says not to follow it right at the top
But ultimately it doesn't matter in the grand scheme of things
imo 88 allows for a bit of padding in case your statement goes just over the limit.
flake8 actually uses 79 char limit
ambv was kind of rude in that discussion, but he explained the rationale. Not much of why it's 88, but why it is now hard to change that default.
<!--
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 `...
I'm guessing they're running a version of 3.11 that doesn't have tomllib
I honestly have no idea though, since 3.11a6 is the most recent prerelease and the docs already have tomllib
yeah probably. GH Actions might not have the latest alpha yet
speaking of 3.11, do we have an issue already for except* support?
Reminder #4276: expires <t:1650918300:R> (ID: 4276)
is the github .git-blame-ignore-rev blame support out of beta? don't forget to attribute https://github.com/henrikhorluck
Reminder #4206: expires <t:1651276650:R> (ID: 4206)
can we test CPython 3.11-dev on GHA yet?
I just installed 3.11.0a6 and import tomllib errors
I think we merged it after the alpha was released
I just built with pyenv
Python 3.11.0a6 (main, Mar 31 2022, 16:53:31) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tomllib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tomllib'
chymera@decohost ~/src/dandi-cli/dandi/tests $ git commit .
Trim Trailing Whitespace.................................................Passed
Fix End of Files.........................................................Passed
Check Yaml...........................................(no files to check)Skipped
Check for added large files..............................................Passed
black....................................................................Failed
- hook id: black
- e...
The following snippet makes black fail with "Black produced code that is not equivalent to the source.".
import typing as t
class Named(t.Protocol):
# fmt: off
@property
def title(self) -> str: ...
class Factory(t.Protocol):
def __call__(self, **kwargs) -> Named: ...
# fmt: on
The following works:
import typing as t
class Named(t.Protocol):
# fmt: off
@property
def title(self) -> str: ...
# fmt: on
class Factor...
I was just testing Black, and one of the outputs I noticed was this, where some code was apparently split up despite similar code next to it being left alone. I think Black's algorithm is counting comment line length against actual functional code line length, which produces a strange inconsistent result. My feelings about the comment aside, I think this output looks strange.
- assert correctResultDictionary["download_command_list"] # check for the existence of correct result files...
I think we should accept a tab argument.
About damn time
Tabs are the best.
See #2965
I left the version check in place because mypy doesn't generally like try-excepted imports. I didn't try directly though.
Describe the bug
Black should follow PEP 9001, the final and preferred style for all Python code. PEP 8 was superseded and is now deemed to be pinnacle of ugly.
To Reproduce
For example, take this (ugly) code:
def add(a, b):
return a + b
And run it with these arguments:
$ black file.py
The resulting (still ugly) code is
def add(a, b):
return a + b
**Expected b...
Thanks for improving the FAQ! congrats on your first PR here :)
3451502 Bump peter-evans/find-comment from 1.3.0 to 2 (... - dependabot[bot]
5436810 Bump peter-evans/create-or-update-comment from ... - dependabot[bot]
Can confirm 3.11.0a7 should contain tomllib. Thanks!
Thanks! @ichard26 did you want to do another review?
lol, great timing here
Description
Spotted a broken link in the README so updating
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
Description
Closes #2041. Allows us to better control placement of return annotations.
a) removes redundant parens:
def foo() -> (int): ...
becomes
def foo() -> int: ...
b) moves very long type annotations onto their own line:
def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2
becomes
def foo() -> (
intsdfsafafafdfdsas...
Yes, but the sheer amount of syntax tree code involved scares me :)
I'll get to it soon, I'm just cleaning up some of my various spreadsheets
Thanks! Some small feedback
that's a very fast review cycle for a formatting PR π
I'm still reviewing / editing psf/black#2926
I won't merge it yet
Great clean work once again, thank you so much! #NewBlack
we should probably just rewrite this test as it's doing nothing ever since click 8 renamed its die on LANG=C function
it's complaining about test_black.test_shhh_click
The more I look at our docs, I wish we had prettier URLs that used dashes and had no file extensions, but would break a lot of links so that's probably not feasible (unless we set up an ridiculous amount of redirects).
Thanks anyway!
Building wheels for collected packages: aiohttp, frozenlist, multidict, yarl
Building wheel for aiohttp (pyproject.toml): finished with status 'error'
error: subprocess-exited-with-error
Γ Building wheel for aiohttp (pyproject.toml) did not run successfully.
β exit code: 1
β°β> [22 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build/lib
creating build/lib/aiohttp
copying aiohttp/web_ws.py -> build/lib/aiohttp
copying aiohttp/worker.py -> build/lib/aiohttp
copying aiohttp/multipart.py -> build/lib/aiohttp
copying aiohttp/web_response.py -> build/lib/aiohttp
copying aiohttp/client_ws.py -> build/lib/aiohttp
copying aiohttp/test_utils.py -> build/lib/aiohttp
copying aiohttp/tracing.py -> build/lib/aiohttp
copying aiohttp/web_exceptions.py -> build/lib/aiohttp
copying aiohttp/web_middlewares.py -> build/lib/aiohttp
copying aiohttp/web.py -> build/lib/aiohttp
copying aiohttp/http_exceptions.py -> build/lib/aiohttp
copying aiohttp/web_app.py -> build/lib/aiohttp
*********************
* Pure build *
*********************
error: can't copy 'aiohttp/streams.py': doesn't exist or not a regular file
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Building wheel for multidict (pyproject.toml): started
Building wheel for multidict (pyproject.toml): finished with status 'done'
Created wheel for multidict: filename=UNKNOWN-0.0.0-py3-none-any.whl size=965 sha256=f28320f7795a1425546c789fd3e7e8610cd6b2e9a4e06951d985ed4efd5a816e
Stored in directory: /Users/runner/Library/Caches/pip/wheels/e4/80/84/c322ab45d6218ff609d81de8343014271fec74423a3b9bfbe7
WARNING: Built wheel for multidict is invalid: Wheel has unexpected file name: expected 'multidict', got 'UNKNOWN'
Not sure why it's now crashing as aiohttp=3.8.1 is not recent at all
could just be random
cosmic ray hit the streams.py inode?
that would've been a real fun april fools, CI crashes due to a cosmic ray βοΈ
anyone know why black sometimes doesn't conform with pep8
Can you give examples?
like, instead of
[item1,
item2,
item3]
it does
[
item1,
item2,
item3,
]
i think i've read somewhere in pep8 that the first one is preferred? i may be wrong rhough
Seems like you should read PEP 8 before claiming Black doesn't conform with it π
Traceback (most recent call last):
File "/home/runner/work/monty-python/monty-python/.cache/py-user-base/bin/black", line 8, in <module>
sys.exit(patched_main())
File "/home/runner/work/monty-python/monty-python/.cache/py-user-base/lib/python3.9/site-packages/black/__init__.py", line 1372, in patched_main
patch_click()
File "/home/runner/work/monty-python/monty-python/.cache/py-user-base/lib/python3.9/site-packages/black/__init__.py", line 1358, in patch_click
from click import _unicodefun
ImportError: cannot import name '_unicodefun' from 'click' (/home/runner/work/monty-python/monty-python/.cache/py-user-base/lib/python3.9/site-packages/click/__init__.py)
psf/black#2964
ye i figured updating dependencies would help
waiting for them to finish updating lol
now i get to relock it again since i had a 21.x build
hm
what is the policy on backports with the new stability policy
meaning we'd release 21.x.x now? :D
Description
Closes #275. Remove redundant parentheses around awaited coroutines/tasks.
This is a tricky one as await is technically an expression and therefore in certain situations requires brackets for operator precedence.
However, the vast majority of await usage is just await some_coroutine(...) and similar in format to return statements. Therefore this PR removes redundant parens around these await expressions.
Let's see what diff shades shades has to say...
...
lol
Describe the bug
With structural pattern matching, Black fails with an invalid syntax, even though target version is py310.
To Reproduce
For example, take this code:
from rest_framework import serializers
from audit.models.health_check import ParentModel
class ServiceRelatedField(serializers.Serializer):
def to_representation(self, value):
match value:
case ParentModel():
data = {"name": value.actor.log...
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I'd expect redundant parenthesis in yield to go away too
# Cr@zY Br@ck3Tz
async def main():
yield (
(((((((((((((
((( (((
((( (((
((( (((
((( (((
((black(1)))
))) )))
))) )))
))) )))
))) )))
)))))))))))))
)
tbh a whole bunch of stuff....
# Cr@zY Br@ck3Tz
async def main():
print(
(((((((((((((
((( (((
((( (((
((( (((
((( (((
((black(1)))
))) )))
))) )))
))) )))
))) )))
)))))))))))))
)
yes, there are a few issues about that. @mint barn-git has been sending a series of PRs cleaning up redundant parens in a few places
oh neato
but unfortunately it needs specific code for each case
reminds me of
We don't do backports.
I'd rather not do backports given how much complexity that'd introduce into our development flow, but I'm fine doing post release patches on a purely adhoc basis.
Still not convinced we need to patch the older versions yet as I haven't seen many people ask for it.
I think it doesn't make much sense to do backports within the 22.* releases, since everyone not using preview mode should be able to upgrade safely without formatting changes
Maybe once we release 23.1.0 next year there will be calls to continue 22.* backports. I don't really want to do that though.
What's the best way forward for dealing with the click 8.1+ fallout @dense jungle ?
does anything else need to be done?
Only problem I know of is a CI failure with mypy on our end but that should be fixable
I'm thinking to just update our type ignores and add a click>=8.1.0 pin (so everyone's cached hooks get evicted)
oops sorry I meant our lint job specifically
sure
Description
The 8.0.x series renamed its "die on LANG=C" function and the 8.1.x series straight deleted it.
Unfortunately this makes this test type cleanly is hard, so we'll just lint with click 8.1+ (the pre-commit hook configuration was changed mostly to just evict any now unsupported mypy environments)
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation? -> n/...
man, there's a typo in the commit message >.<
Please refrain from spamming on topic channels @naive wren .
!remind 20H try to respond to https://github.com/psf/black/issues/2883 ...?
Your reminder will arrive on <t:1649188660:F>!
Actually, this will need a NEWS entry. You can see examples on other open PRs.
fa5fd26 Update test_black.shhh_click test for click 8+ ... - ichard26
421383d Update FAQ: Mention formatting of custom jupyte... - kolibril13
This is not a bug, but a general question.
Sorry, I could not ask this question on Discord as it keeps telling me I'm in an unclaimed account even though I've logged in.
black has listed in its distribution meta-data top_level.txt the module 610faff656c4cfcbb4a3__mypyc. I'm wondering how the name of this module is generated as it is not found in src/.
Description
I needed to remove the 365-day data from https://hugovk.github.io/top-pypi-packages/ because it was using more quota than available, so let's just use the 30-day one instead.
Also use the minified version for a bit smaller file.
Re: https://github.com/hugovk/top-pypi-packages/pull/21, https://github.com/hugovk/top-pypi-packages/pull/20, https://github.com/hugovk/top-pypi-packages/issues/19.
Checklist - did you ...
- [ ] Add a CHANGELOG entry ...
hey, is there a way to make black use single quotes instead of double quotes?
no
hm
black is opinionated like that.
You can probably force it on an individual basis by using a " character in your string.
Here's your reminder: try to respond to https://github.com/psf/black/issues/2883 ...?
[Jump back to when you created the reminder](#black-formatter message)
Description
Closes #1872.
Does 2 things:
a) First commit is a slight refactoring of EmptyLineTracker to remove the after return.
The reason being that it's only there because the current implementation wouldn't let you look back more than one line, which as a consequence means any logic that defines a before would need account for the possibility that the previous line returned an after and makes it hard to separate the logic of individual rules.
Now we just scan through ...
Thanks!
It occurs to me that maybe we shouldn't be formatting # fmt: skip comments at all, even adding the space. But I am not going to worry about that until and unless users actually complain.
Description
Closes #2992. Updates the --version flag to include details of python version running black.
e.g.
black, 22.1.1.dev56+g421383d.d20220405 (compiled: no)
python, 3.9.12 (CPython)
I've also included the python implementation in case we ever get PyPy (or other implementation) specific issues.
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
Describe the bug
When strings are concatenated, originally having been split on multiple lines, the result contains breaks that are unnecessary and conflict with tools like pylint: -
_LOGGER.warning('Got ApiException' ' listing namespaced pod' ' (%s)', ex)
To Reproduce
Start with a string split over multiple lines, typically in a logger call.
For example, take this code:
_LOGGER.warning('Got ApiException'
' listing namespac...
It's nice not having to review AST mangling code, it's always a bit of a pain to review. π
f6188ce Output python version and implementation as par... - jpy-git
if anyone feels like debugging why black's test suite is failing with the latest development versions (i.e. from the main/master branch) here ya go: https://github.com/ichard26/black-deps-ci/actions/runs/2105909618
I'll note that it's only failing on Python 3.8 and higher since only those versions are supported by the latest versions of the jupyter deps (or at least that's my guess)
The documentation currently recommends using the sublack extension but the repo was archived February 28, 2022 and is no longer maintained.
I am not super conscious which version of Sublime Text I have since version 4 doesn't really advertise it, it's just "Sublime Text" and the About window has a build number rather than a version number. So "Sublime Text" caught my eye in the docs. After looking into the LSP option, I finally figured out I'm on version 4 and the LSP path was the right ...
For input code that looks like this:
def f(a: Optional[Union[int, str] = None):
"Make sure this code is blackened"""
pass
Same versions of black seem to modify the code differently. Both usages have black version 22.3, pip installed, compiled: yes.
My ubuntu leaves the code unchanged. However, my MacOS, changes it to:
def f(a: int | str | None = None):
"Make sure this code is blackened"""
pass
How can I make my MacOS versio...
@stuck vapor could you take a look into this? installing ipython from github main fails test_ipynb.test_set_input
def test_set_input() -> None:
src = "a = b??"
with pytest.raises(NothingChanged):
> format_cell(src, fast=True, mode=JUPYTER_MODE)
E Failed: DID NOT RAISE <class 'black.report.NothingChanged'>
from black import format_cell, Mode
src = "a = b??"
dst = format_cell(src, fast=True, mode=Mode(is_ipynb=True))
print(repr(dst))
you can notice the difference using this
here's the diff between ipython 8.2.0 and main: https://github.com/ipython/ipython/compare/8.2.0...master
Python allows splitting long string using following syntax (note lack of comma)
def quite_short():
return ("foo"
"bar")
def very_long():
return ("57bacf6898da8b257bc5b0c1d6b13e9a7551f17ea30a0a306eaa68f51243fcbc"
"f2b176250dbc8eae0c97650396658c28576a18e3ec8759d6fcfedabbf8577a5d")
Resulting value is concatenation of parts, without any separator. Here is how black(1)
reformats this snippet:
def quite_short():
return "foo" "bar"
def very_lo...
:incoming_envelope: :ok_hand: applied mute to @sick patrol until <t:1649408812:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 119 newlines in 10s).
@sick patrol Please stop spamming your question everywhere. Open a help channel #βο½how-to-get-help
!unmute 764471561343336490
:incoming_envelope: :ok_hand: pardoned infraction mute for @sick patrol.
You want to help with black's development? Could you elaborate? :)
well all of my projects' CI is failing thanks to the click issue, this is quite annoying :)
this time it's diff-shades 
I've just tried out black for my project, it looks great. But I'm a bit confused about this change
Does it only add commas when function calls and the like are multiline? And, what's the motivation behind it?
The idea is that for collections the trailing comma allows for easier adding of new elements or editing, since the rows are uniform.
i.e. calls, lists, dicts etc.
im sorry if this place isn't for asking help, but would you guys happen to know why im getting this error whenever i try to use black?
$ black test.py
/usr/bin/env: './python3': No such file or directory
i am on android, but using replit which runs on linux afaik
i was able to fix it with someone's help (#help-rice message) by changing the first line of this file from #!/usr/bin/env -S ./python3
but would you happen to know if this is a permanent fix or a hacky fix?
using python -m black instead of black when running black is probably a good workaround
I'm not familiar with REPL to know what it does that causes the built entrypoints to not work
oh i see i see, that worked. thanks!
Excellent work @jpy-git :tada:
98fccce Better manage return annotation brackets (#2990) - jpy-git
https://github.com/psf/black/blob/22.3.0/src/black/__init__.py#L1438 of course this is breaking diff-shades CI on main
src/black/__init__.py line 1438
from click import _unicodefun```
it's missing a type annotation -- the baseline revision (being 22.3.0) fails to compile now
not sure how I built the mypyc wheels without error now I think about it though
maybe you had click 8.0.1 installed?
mypyc-requirements.txt lines 5 to 13
# A bunch of packages for type annotation information
mypy-extensions >= 0.4.3
tomli >= 0.10.2
types-typed-ast >= 1.4.2
types-dataclasses >= 0.1.3
typing-extensions >= 3.10.0.0
typing_extensions != 3.10.0.1; python_version >= '3.10'
click == 8.0.4
platformdirs >= 2.1.0```
Beautiful work! I think I'm also getting better at reading code involving blib2to3's CST.
Thank you once again!
75f99bd Remove redundant parentheses around awaited cor... - jpy-git
LGTM, thank you and congrats on your first contribution to psf/black @siuryan! -- always nice to see some new faces :)
431bd09 Correctly handle fmt: skip comments without int... - siuryan
Description
While responding to GH-2994 I realized we don't have a FAQ entry about this, let's change that so compiled: yes/no doesn't surprise as many people :)
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- [x] Add / update tests if necessary? -> n/a
- [x] Add new / update outdated documentation?
I used a spell checker and read over my writing a few times over, hopefully that shows :)
Huh, I thought there's more projects on diff-shades's list
I just stole black-primer's list of projects and added a few of my own projects :p
I'm sure it's millions of lines of code anyway, just didn't think it would be just 20 or so projects π
... out of 2 178 151 lines, 10 484 files & 23 projects
roughly two million :)
django and typeshed are responsible for a sizable portion IIRC, along with pillow or pandas?
I can't remember Β―_(γ)_/Β―
https://github.com/psf/black/pull/2996#issuecomment-1089417251 I like this comment, it makes me happy to see it.
Could be further improved, like including a breakdown of the changes per project or whatever (hidden in a dropdown), but it's good as it is.
hmm, actually that feature would've probably saved jpy-git some work
gosh it's been a while since I've last ran this script. haven't used it much ever since I made https://ichard26.github.io/ghstats/
@dense jungle btw could you update the stable tag? I don't have access to my main Linux machine right now (I'm stuck waiting for windows updates to finish)
whee thank you!
pip install black
There are extensions for various IDEs available
It's part of the standard Python extension, so there's no need for a Black-specific one
you have to enable it
the instructions linked in the documentation you quoted
well it formats your code, so the most the integration will do is make it easier to run black (by adding a shortcut or even automatically running it)
sorry just saw this - will take a look
In the latest release of IPython:
>>> TransformerManager().transform_cell('a = b??')
"get_ipython().set_next_input('a = b');get_ipython().run_line_magic('pinfo2', 'b')\n"
In the development version:
>>> TransformerManager().transform_cell('a = b??')
"get_ipython().run_line_magic('pinfo2', 'b')\n"
The latest version looks more correct to me, because the a = part will be ignored anyway if you type that line into an IPython shell:
In [2]: object??
Init signature: object()
Docstring:
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless
instance that has no instance attributes and cannot be given any.
Type: type
Subclasses: type, weakref, weakcallableproxy, weakproxy, int, bytearray, bytes, list, NoneType, NotImplementedType, ...
In [3]: a = object??
Init signature: object()
Docstring:
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless
instance that has no instance attributes and cannot be given any.
Type: type
Subclasses: type, weakref, weakcallableproxy, weakproxy, int, bytearray, bytes, list, NoneType, NotImplementedType, ...
So I think I'd suggest to update the test.
What's the process for dealing with dev versions of dependencies? Should one wait until the next IPython release to update the test?
currently working on upstreaming the mypyc workflow, hopefully this doesn't crash
and I managed to mess twice, once by forgetting a few changes and twice by using the wrong commit message initially
The code looks solid but I'd still rather not put a blank line at the beginning of each docstring. I'd be curious to hear other maintainers' opinions.
Hi, I am trying to install black and use in Vscode Jupter notebook using pip install black[jupyter]. But, I get an error : zsh: no matches found: black[jupyter]
Is your feature request related to a problem? Please describe.
Black does not support the new structural pattern matching pattern in 3.10
Describe the solution you'd like
Add match...case to the parser
Describe alternatives you've considered
Additional context
How can I make a command to be only used in a server
Not in other servers
Like id: 123456
And the command should be used in the server with this id only
Sounds like your shell is trying to do command expansion. Try quoting the part with the square brackets: pip install "black[jupyter]"
We just got someone on Discord who was confused because the command as written caused their shell to try to do command expansion.
You have to select black in the "Provider" list. After that, you can do Ctrl+Shift+I on Linux or Alt+Shift+F on Windows to format the current file.
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
xref https://github.com/ichard26/black-deps-ci/actions/runs/2105909618 - one test is failing due to changes in IPython
In the latest release of IPython:
>>> TransformerManager().transform_cell('a = b??')
"get_ipython().set_next_input('a = b');get_ipython().run_line_magic('pinfo2', 'b')\n...
Man, huge thanks for taking on all these issues!
I think I'd prefer the newlines to be added to multiline docstrings as well, just for consistency. Not strongly though, and against my own habits and what I said in the original issue I know, but still.
About the preview handling: certainly this is a feature we'd carry over without question, so no biggie, but having the clarity of being able to search for usages of a potential Preview.docstring_newlines (or similar) was intended to help...
those are touching different files @errant barn
...... I'm
haha at least you closed Jelle's PR :p
fk, at least someone is awake
Is your feature request related to a problem? Please describe.
Consider the following un-blackened code:
@dataclass
class FooBar:
message: ClassVar[str] = """\
This is just an example of a long string literal. \
This is just an example of a long string literal.\
"""
This is represents (for me) a very common situation: Methods within a dataclass need to use a constant string that's too long to readably inline into code, so it's moved to a class attribute, where i...
it's only 5:17 PM over here on the better other side of the pond
I think I'll sleep now
good call :)
911b59f Bump furo from 2022.3.4 to 2022.4.7 in /docs (#... - dependabot[bot]
96bd428 Quote black[jupyter] and black[d] in installati... - JelleZijlstra
do single quotes work in Windows
I have no idea Β―_(γ)_/Β―
just tested, it works in powershell but not cmd
well that's fun.
oh good catch, do double quotes work in both?
ye
yes
and they don't expand in zsh
which I actually find a bit weird considering how other things expand in double quotes but I'll take it
yay for os tridiversity
ok thanks for checking! someone wants to make another PR? π
I actually ran into that problem with extras previously and had to update docs in a different project so I was guessing there must have been something about single quotes that isn't going to work considering the docs in that project are using double quotes lol
In regards to method chaining, should black try to automatically reformat this into multiple lines without the user having to explicitly add parentheses.
From:
# Exceeds 88 character limit
apple = Fruit()
apple.eat().remove_seed().plant_seed().eat().remove_seed().plant_seed().eat().remove_seed().plant_seed()
To:
apple = Fruit()
(
apple.eat()
.remove_seed()
.plant_seed()
.eat()
.remove_seed()
.plant_seed()
.eat()
.remove_seed()
.plant_seed()
)
I know this is a bad example
I believe black does not do things like that for AST safety but I am not 100% sure
black does the ORM thing (fluent interface) inside parens but you have to opt-in I guess
I don't think it's typical to split like this in non-fluent interfaces
this doesn't change the AST
so I feel like doing reformatting in such cases would look weird
There is a --preview flag or something like that to enable changing the AST I believe
not exactly sure
It's for switching on experimental style changes, not an AST toggle
hmm, I'm not 100% but we try to keep AST changes very minimal so I'd be surprised
although if the proposed docstring changes land it would be another case
okay thanks for the information
I remember I saw something like that mentioned somewhere
some conversation about an AST toggle in psf/black#2150 though if you're interested!
thanks
black formatter
Playground, or code sample:
user_info = {
'worker': _make_worker_info,
'requester': _make_user_info,
}[user_type](user)
hmmm I don't know what I was thinking saying that
IIRC I was the person that SO answer quoted
what is this about
How's the progress with this?
I plan on having an ast, and wanting to output it using black
not much has happened for a while
Finally I can stop getting notifications because black-deps-ci's CI is failing daily :D
712f8b3 Make ipynb tests compatible with ipython 8.3.0+... - MarcoGorelli
do you mean .*pycache.*? Black uses regexes not globs
Hello
Is your feature request related to a problem? Please describe.
Linters rightfully complain when a line is too long, and black does try to split lines, but this seems to not include some cases at the moment. An example:
def some_very_very_very_very_very_very_very_very_very_very_very_very_long_function_name():
pass
some_very_very_very_very_very_very_very_very_very_very_very_very_long_function_name()
a = {
# configured with a line length of 100, pylint comp...
Python 3.11 adds the new except* syntax in PEP 654 (https://peps.python.org/pep-0654/#except). We should support it. I think this should be a straightforward change to the grammar.
We should also normalize formatting, e.g. change except *E: to except* E:. (There was a long python-dev thread about how to format it and I believe that was the consensus outcome.)
@isidentical are you interested in this as our resident parser expert?
'exclude' in pyproject.toml does not exclude the file
In the root directory of my project I added a pyproject.toml file and added exclude = 'build.py and I execute pre-commit run in my terminal. But build.py is still modified
To Reproduce
- Create a sample project directory with folders like src, test
- In the project directory create this configuration file
pyproject.toml: ``` # Configuration for black pre-commit
[tool.black]
exclude = '''
build.py
'''
`...
PEP 646 ads two new pieces of syntax in 3.11 (https://peps.python.org/pep-0646/#grammar-changes):
x[a, *b]def f(*args: *T): pass
We should support both and normalize the syntax to have no space after the * (also cc @isidentical).
Perhaps we should document this issue in the FAQ? Using pre-commit with Black is pretty common (and it's not always instantly clear it passes all of the files to the hook directly bypassing any file discovery the hook may implement). I'd suggest pre-commit's exclude configurations first, and then black's force-exclude.
_Originally posted by @ichard26 in https://github.com/psf/black/issues/3013#issuecomment-1099704336_
For context, we added the --force-exclude option as pre-com...
!remind list
Reminder #4373: expires <t:1650146279:R> (ID: 4373)
does black have 1337 commits?
Reminder #4276: expires <t:1650918300:R> (ID: 4276)
is the github .git-blame-ignore-rev blame support out of beta? don't forget to attribute https://github.com/henrikhorluck
Reminder #4206: expires <t:1651276650:R> (ID: 4206)
can we test CPython 3.11-dev on GHA yet?
we don't even run tests on python 3.11-dev
Looks good, thanks for the quick fix!
the blib2to3 change should still work though
Cross-platform. This is off topic for this channel though :)
Or OS-independent.
Ah cool. Well anyway welcome to Python Discord! This is the #black-formatter channel where the core team and other community members discuss the Black python autoformatter.
#python-discussion is our all purpose general discussion channel. Under it we have some off topic channels and also some discussion channels ( #internals-and-peps #community-meta etc.)
https://github.com/psf/black/runs/6032901934?check_suite_focus=true ugh, Python 3.11-dev still won't work as Cython haven't done a new release yet.
nice
um
this channel is for the black formatter
but nice language though, looks like C and Python's baby
this is annoying, how do i make it not annoying
--line-length 100
where do i input that?
You pass it in via the command line or you can put it in your pyproject.toml (or however you configure black)
Description
This makes changes across workflow domains easier (like adding concurrency limits) and overall improves consistency. I plan to submit another PR integrating the mypyc workflow from ichard26/black-mypyc-wheels after this is merged. Here's an example run: https://github.com/ichard26/black/actions/runs/2144614522 (including the mypyc patch)
This is probably best landed with a rebase merge fyi.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> ...
If folks disagree that consolidation is better, please let me know! I'll add the mypyc workflow/jobs regardless where this PR goes.
it may be easier to review using git locally @dense jungle , unchanged lines (that only moved files) are visible locally
OK cool git diff main... should show the right context (after gh pr checkout 3017), I forgot how to merge diff a branch to main
Oh neat, GitHub for Mobile finally shows the workflow name prefix in the checks list UI. That kinda kills half the value of this PR though 
Describe the bug
Black collapses lists in return type annotations onto one line, regardless of the "magic" trailing comma.
To Reproduce
For example, take this code:
@hl.generator(name="simplepyfn")
def SimplePyFn(
context: hl.GeneratorContext,
buffer_input: Buffer[UInt8, 2],
func_input: Buffer[Int32, 2],
float_arg: Scalar[Float32],
offset: int = 0,
) -> tuple[
Buffer[UInt8, 2],
Buffer[UInt8, 2],
]:
"""
... more cod...
@bright glacier Wow @ your large ass .yml actions
TIL a lot
How does the concurrency work?
LGTM - How do we test this tho?
Want to update bandersnatch to this cause I do have a release I need to do, would rather screw up a bandersnatch release than black :D
The answer is that I tested it out as much as I reasonably could on my repo
I disabled the docker upload and pypi upload bits but left everything intact and did a test release
I linked to the workflow run in the PR description @neon loom
I must be blind. Cheers. Thatβs good enough then
Any idea with this or should I be less lazy and go find docs?
I'll be able to explain once I'm back on my laptop, currently on my phone :p
afaict, the concurrency.cancel_in_progress means that something like this will happen:
- currently, PR #12345 is running the Lint workflow
- the author quickly pushes a commit to PR #12345 while the previous Lint is still running
- the old Lint immediately stops and a new Lint workflow is run
without it, the old Lint and the new Lint will run, which is probably a wasted workflow run
(I may be wrong on that, that's just my understanding of it)
It's exactly that
... the run_id OR fallback is for workflows that aren't linked to a pull request, they will use an ID unique to each run
probably a silly question, but why does black remove the single empty line here?
if True:
foo
bar
no?
hum, i guess the playground is broken, then? i tried here https://black.vercel.app/
it works fine for me in firefox, but is broken in chrome and edge, hum
I'm on chrome Β―_(γ)_/Β―
oh god, what on earth is happening
I have no idea. We don't control the playground btw, JosΓ© Padilla does
this is funny, if i open your link, it works fine. if i open your link, and copy-paste your code in place, it works fine. but if i open your link, paste the code into notepad, copy it from there, and paste it back, it breaks
yup
i guess i'll see if they've got an issue for this
in inspector it shows that your payload has \r\n newlines and @bright glacier's has \n
yeah, I was thinking something like that was the problem. i'll make an issue i guess. i'll mention this
let me see if I can repro this with Black directly
doesn't repro on the command line
aha, thanks! i'll mention this too, then.
can i also ask something else. i ran black on my tests and it did this, although the documentation seems to be saying that black likes call chains? https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AGRAOldAD2IimZxl1N_WlXnON2nzOXxnCQNGadArwI9yclOzPPmLbUxjbxC6mtuVV_e4twQ-I1pjv2w0mNjcCzcXh6X4gcvLDct8vjHtypdFJYoO3igalTFV4Cuyqu3sjr16j__A5Gb0cit769ikJS5GW1RgMvqycH9Aajuk2uQvEN4kiCbe0gcOSkzaXUb8KTpAU3mkgSC3LbuxIF3T06UhBHDMuGn9hyWYozhMwFxzcgGULUY7XtDaR4eowPYQvFJrg-f3k0ABCq5oOdehG_qBV8I8e525rsKELHORgSI9ZREYaJfQxtz50w1pocAAAAAACsLGfWQ8s--AAGFApIDAACglefiscRn-wIAAAAABFla
only in some circumstances, not sure we ever do it within lambdas
black used to be amv/black for the plugin in vim what is it now?
wait
how do i get the latest version of black (i think it came with PEP 9 or smthn?) for neovim?
I don't use it myself, but check out https://black.readthedocs.io/en/stable/integrations/editors.html#vim
If I suspect mypyc is generating invalid C code for Black, how do I prove that? How can I see the intermediate .c files that get built by mypyc in the process of creating a wheel for Black?
they're not stored anywhere in the built wheel AFAIK
(I'm trying to track down https://github.com/psf/black/issues/2845 - the segfault is uninteresting, but the assertion error is interesting)
the C output is stable though so I could probably generate it locally looking at the build logs
looks like the problematic type is StringMerger, and it looks like mypyc is generating code that sets tp_vectorcall_offset and Py_TPFLAGS_HAVE_VECTORCALL without setting tp_call, which would be wrong.
OK, according to the logs the 22.3.0 wheels used mypy==0.910
I'm familiar with the C API, but I know approximately nothing about mypyc - but that assertion error certainly seems to indicate that the code it's generating is wrong...
ah! Looks like the class is inheriting __call__ from its superclass. That's probably the test case here...
assuming you don't care what version of mypy / black you're using, simply running python setup.py --with-mypyc bdist_wheel and stopping it once it hits running bdist_wheel will allow you dig into build/ for the __native*.c file
you might need some extra packages for give mypy more type information, feel free to use this list: https://github.com/ichard26/black-mypyc-wheels/blob/9bd31a4592455d91cb6a505baa8dce6b29e3d21e/mypyc-requirements.txt#L5-L13
mypyc-requirements.txt lines 5 to 13
# A bunch of packages for type annotation information
mypy-extensions >= 0.4.3
tomli >= 0.10.2
types-typed-ast >= 1.4.2
types-dataclasses >= 0.1.3
typing-extensions >= 3.10.0.0
typing_extensions != 3.10.0.1; python_version >= '3.10'
click == 8.0.4
platformdirs >= 2.1.0```
(I'll note that mypy beyond 0.910 generates very broken code currently for black so you'll want to use that if you're compiling black)
ack - I'm gonna try messing around without Black and seeing if I can reproduce this for a minute, now that I think I've spotted what's interesting about what Black is doing...
yep! It's pretty trivial to reproduce now that I guessed what's going wrong.
$ cat test.py
class Base:
def __call__(self) -> None:
return None
class Derived(Base):
pass
$ mypyc test.py >/dev/null
$ python3-dbg -c 'import test'
../Objects/typeobject.c:5392: PyType_Ready: Assertion "type->tp_call != ((void *)0)" failed
Enable tracemalloc to get the memory block allocation traceback
object address : 0xc518a0
object refcount : 1
object type : 0x97cbe0
object type name: type
object repr : zsh: segmentation fault (core dumped) python3-dbg -c 'import test'
the segfault is uninteresting (it's trying to print an object that hasn't yet been fully initialized, and it's accessing a field that hasn't yet been set), but the assertion error is either a bug in CPython, or a bug in mypyc
Crash Report mypyc generates code that triggers a CPython assertion when a subclass inherits call from a superclass. To Reproduce $ cat test.py class Base: def call(self) -> None: re...
thank you! @glad pilot
It's selfish - I keep bumping into this because I keep installing my own modules into a venv made by a debug interpreter to test it out, and then forgetting I'm using a debug interpreter, installing my linters, and segfaults π
I mean, it's probably just black segfaulting
... well hmm mypy is compiled itself but I haven't seen any reports of that
the assertion error message didn't quite give enough context to see what was happening, but it was easy enough to figure out once I applied some gdb
FWIW, I highly recommend testing C extension modules with a debug build of the interpreter
it catches lots of subtle bugs - if you're going to be including mypyc-generated stuff, running python3-dbg in your test suite would be a good idea
Hmm, how would that work with cibuildwheel?
absolutely no idea. π
ah, well then I'll figure it out eventually
probably worth adding a mypyc build CI job for pushes to main
diff-shades (runs on pushes to main and PRs) tests mypyc indirectly but it doesn't use a debug build of cpython
I'm completely new to github actions - looks like Pablo didn't set up anything using -dbg interpreters for memray, so... π€·
Maybe it matters more when you're writing your extension code by hand, and less when mypyc is generating it for you, though.
I'm pretty sure mypyc is still technically alpha even though black and mypy are both using it π
I believe so, yeah.
Has it already been tried to get black to use mypyc when it's run as a pre-commit hook?
why wouldn't it use mypyc then?
it's annoying since pre-commit clones black from github directly avoiding the compiled wheels. This is also why --required-version breaks with pre-commit :/
Timing from running on the pandas codebase:
With standard pre-commit hook, i.e.
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
$ rm -rf ~/.cache/black/; time pre-commit run black --all-files
black....................................................................Passed
real 0m31.356s
user 5m33.922s
sys 0m1.585s
With local hook, i.e.:
- repo: local
hooks:
- id: black
name: black
entry: black
types_or: [python, pyi]
language: python
additional_dependencies: [black==22.3.0]
$ rm -rf ~/.cache/black/; time pre-commit run black --all-files
black....................................................................Passed
real 0m14.093s
user 2m29.339s
sys 0m3.660s
Problem is, trying to get it to use mypyc when installing as part of the pre-commit hook results in
File "setup.py", line 42, in <module>
from mypyc.build import mypycify
ModuleNotFoundError: No module named 'mypyc'
Do you know if there's a package on PyPI which contains everything necessary to run mypyc?
you'd need to install mypy and a bunch of dependencies (or their types- counterparts) so mypy[c] has enough type information
I should probably document this somewhere in the development docs.
Thanks - just tried with
additional_dependencies: [
mypy,
mypy-extensions,
tomli,
types-typed-ast,
types-dataclasses,
typing-extensions,
click,
platformdirs,
'setuptools-scm[toml]',
wheel
]
but still get
from mypyc.build import mypycify
ModuleNotFoundError: No module named 'mypyc'
that's because it's a build time dependency (along with the others)
when pre-commit shells out to pip to install the local clone, the [build-system] table in pyproject.toml will only have setuptools, setuptools-scm, wheel available
π€ reckon there's some other way around this then?
the cleanest way would probably be to use a shim repository that installs black from pypi or builds black manually, but that seems untenable
might go with a local hook then, with as many files as pandas has it makes quite a noticeable difference
Perhaps we could make another repo that does this, but it wouldn't be great being able to use different repos as the source
python packaging overall doesn't support conditional build time dependencies very well, aiohttp has to deal with this too
does mypy itself deal with this when it is used as a pre-commit hook?
I have no idea but everyone uses it as a hook via another repository so in theory they could do some fancy setup.py logic to workaround this
well that's certainly one way to use the compiled wheels in pre-commit
it seems like these mirrors are automated which is neat. I'd imagine they don't support specifying commit SHAs, but that's fair.
adding these to pyproject.toml , I no longer get that ModuleNotFoundError, now it's just
Parsed and typechecked in 2.211s
Compiled to C in 0.000s
src/black/parsing.py:30:1: error: Library stubs not installed for "typed_ast" (or incompatible with Python 3.8)
src/black/parsing.py:30:1: note: Hint: "python3 -m pip install types-typed-ast"
src/black/parsing.py:30:1: note: (or run "mypy --install-types" to install all missing stub packages)
src/black/parsing.py:30:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
src/black/parsing.py:30:5: error: Name "ast3" already defined on line 25
which is odd because types-typed-ast is definitely in there π€
that's strange :/
it's a different error to the one before though, so it's progress π π
i'll quickly note that IIRC gcc doesn't work with mypycified black on linux btw, you'll want to use clang
I don't know where you are in the process but I'd like to highlight that speed bump ahead of time
Is your feature request related to a problem? Please describe.
Going for a more complete CI process, which includes committing formatted code as a requirement
Describe the solution you'd like
A command, such as black lint which does dry runs and exits zero if everything is already formatted, but returns 1 or some other non-zero value if any files or lines remain to be formatted.
Describe alternatives you've considered
Reading stdout for unchanged vs. reformatted
Black has negatively affected the neatness of the code I write π
I just write dirty code out of laziness and run black
But with less effort I presume!
Describe the bug
Flake8 E0203 doesn't like spaces before colons
Black is placing spaces before colons in the code below
Personally I agree with Flake8 on this one but I'm not sure who is "right" here
To Reproduce
Take this code:
@staticmethod
def id_from_lookup_key(lookup_key: str) -> int:
if lookup_key.startswith(Price.LOOKUP_KEY_PREFIX):
return short_url.decode_url(
lookup_key[len(Price.LOOKUP_KEY_PREFIX) :] # ...
Is this related to a problem? Please describe.
On https://black.readthedocs.io/en/stable/usage_and_configuration/black_docker_image.html there is link to Docker Hub, but it is not a HTML link ("a" tag), so you need to copy/paste to open it.
Describe the solution you'd like
Create a HTML link.
Description
#3022 - updated Black Docker Hub link to a valid HTML link.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
This page in the docs has the following text:
You've probably noted that not all of the options you can pass to Black have been covered. Don't worry, the rest will be covered in a later section.
However, I looked through the rest of the docs, and couldn't find this fabled "later section". Does it exist? If so, can the docs be updated to just link to that section instead of alluding to it? If it doesn't...
we might have to file a bug report for myst-parser honestly, I couldn't figure it out either when I last tried π¦
the issue was windows specific IIRC
!remind 21H look into the options PR
Your reminder will arrive on <t:1650571237:F>!
maybe we should just remove the links for now
Description
'true' 'on' in python is 'trueon'
Describe the bug
If you have yapf: enable comments inside an expression, you can cause black to hang:
To Reproduce
with file.py as:
def test_func():
# yapf: disable
if a:
return True
# yapf: enable
elif b:
return True
return False
$ black file.py
It hangs forever.
Expected behavior
It should not hang.
At the very least it should give an error.
Preferably it should ignore those ...
Hey!!
I recently installed black on my arch system. But for some reason it's not working. It's a environment variable problem ig.
I have tried setting path like this:
set PATH /home/name/.local/bin
It works but then other unix commands won't work.
Important : The above solution (sort of) only works in fish. (shell)
Any Solutions for this?
I am not much familiar with environment variables so please don't judge me
generally you want to only add things to $PATH, not replace it completely
something like set PATH $PATH:/some/new/path
I was also thinking the same as setting the path was disabling the other commands
set PATH $PATH:/home/xxx/.local/bin
This should work right?
yes. note that putting it at the end makes it lowest priority, so if there a black in an earlier PATH entry it will be preferred
Thanks, that's embarrassing.
Since this fixes a user-facing bug, could you add a news entry?
Is your feature request related to a problem? Please describe.
When working with a new project is often difficult to find out where the developers have placed all the configs for the different tools they are using. Some choose to add then to pyproject.toml, others to tox.ini, others to setup.cfg, others write the settings for some tools in one place, and the settings for other tools in another... this is most definitely confusing for new contributors, and in many cases cannot b...
8ed3e3d Updated Black Docker Hub link in docs (#3023) - JiriKr
Here's your reminder: look into the options PR
[Jump back to when you created the reminder](#black-formatter message)
Can black-formatter format my casing style?
I used it, and it was great, but I have some very bad, inconsistent naming
meaning variable naming?
yes
unfortunately not, that would change the AST, which we try to avoid
I have functions defined in PascalCase, camelCase and snake_case, and lowercase in the project
but a tool like that would be cool!
thanks, I guess I'll have to do it manually
but I have to say, it's really fast and convenient
or spend 10x the time and automate ;D
showed me syntax I didn't even know existed
much appreciated ππΏ
pylint can at least let you know about such issues in your code
But I don't know of anything that would automatically change code to adhere to such convention, seems dangerous :P
I just encountered a bug in on of my project, that was introduced by black: I have a dict variable where one element on a line was deemed too long by black so it split the value, a string, in two. But the string is an f-string and when split, black does not put an f-string on the second line and it happens a {} is on that line. The value is then broken at evaluation
# before black
row_attrs = {
"onclick": lambda record: f"window.location='{reverse('organization_follow_up_detail_view', args=(record.pk,))}';",
}
# after black
row_attrs = {
"onclick": lambda record: f"window.location="
"'{reverse('organization_follow_up_detail_view', args=(record.pk,))}';",
}
It thus broke the lambda. Is that addressed in most recent versions of black or is it a current known bug? Otherwise, I would be more than happy to open an issue.
It's unlikely we ever had that bug. Can you reproduce it running Black directly on a file?
I'm trying right now but I can't reproduce it somehow. Black is run many times a day against the code locally and in a pipeline. I wish I could pinpoint the moment and what triggered that kind of choice. I'll keep trying some scenarios, otherwise that will hard for you to diagnose that so I'll just go with it and I'll open an issue if it ever happens again.
Sure. The reason I say it's unlikely is that we have AST safety checks that should make Black crash if it ever made that change. Those have been there since the beginning. It's slightly more likely that this happened if you run with the --fast and --experimental-string-processing flags.
Gotcha. However I've run Black without any flag, inside a docker container docker-compose run --rm django black .
Thank you for your help and taking time to answer me.
<!--
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 `...
This isn't the right channel to get general help with python, see #βο½how-to-get-help
Formatters increase consistency, which helps readability.
In other words they reduce noise, which can be defined as variability with no attached meaning.
For example - 2 lines instead of one may imply some meaning, but may also be just an arbitrary design choice.
Whenever our minds have to handle with >1 options to interpret something, we have to invest more energy to understand what's going on.
Black does a great job at reducing a lot of ambiguity by rewriting the code.
In other wor...
^ additionally, you often order code to keep related functions together, and black can't know that
agree. and do we order classes and functions separately? and do we do AST analysis to make sure we don't put child classes before base classes?
Some strings looks like they're meant to be f-strings but are missing the f prefix meaning variable interpolation won't happen.
https://github.com/psf/black/blob/8ed3e3d07ea3e6d62e3e533e69f96a0ff148cd5d/tests/data/long_strings__regression.py#L415
https://github.com/psf/black/blob/8ed3e3d07ea3e6d62e3e533e69f96a0ff148cd5d/tests/data/long_strings__regression.py#L416
https://github.com/psf/black/blob/8ed3e3d07ea3e6d62e3e533e69f96a0ff148cd5d/tests/data/long_strings__regression.py#L1035
https://...
for context, code-review-doctor would actually break gallery if it PRed this suggested change
I know automating deep code linting is hard, but I am a bit suspicious of any service that claims it can detect logical issues.
Though, looking through its PR history, this service doesn't seem half-bad, huh
Description
Black's __init__.py file does not explicitly alias imported modules as themselves which is required for type-checking.
I grepped the code for things that were directly called from black. and added X as X for anything mentioned in the code + anything I thought seemed related.
This isn't really very important, I was just annoyed by some of the pyright warnings I was getting when using black.Mode.
Happy to alter the PR in anyway, if you think more or less shou...
TL;DR
There shouldn't be a newline right after def statement.
Describe the style change
Newlines are great. They help us organize our code and leave room for the coders and reviewers to breath.
However, too many newlines can make simple code gigantic and massive. This is unnecessary in a lot of cases.
I want to argue that having a newline right after def is redundant and Black should remove it
Examples in the current Black style
Right now Black won't c...
Description
When testing black formatting, the simple use cases where defined hard-coded in a list named SIMPLE_CASES in test_format.
This is a shame since many times people add a new data case and forget to add it to this list and then it does not run!
Now, one can read all the available cases in a given directory using a method named all_data_cases. This method searches for all the cases in a subdirectory of data and return them as names.
Checklist - did you ...
-...
Description
Fixes #902
Newlines are great. They help us organize our code and leave room for the coders and reviewers to breath.
However, too many newlines can make simple code gigantic and massive. This is unnecessary in a lot of cases.
I want to argue that having a newline right after def is redundant and Black should remove it.
Now, the following code:
def f():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
...
?
Describe the bug
Behaviour of black in adding a single space after the #in in-line comments is inconsistent when single or double quotes is used within the comments. Please see the MWE.
To Reproduce
For example, take this code:
# NOTOK:
# single quote -> double quotes, as expected. But black didn't introduce
# a space after the `#` character on the commented-out line.
string_single = [
'a',
'b',
#'c',
'd',
]
# OK:
# Space added af...
Black Lives Matter guys
π§’
Here's your reminder: is the github .git-blame-ignore-rev blame support out of beta? don't forget to attribute https://github.com/henrikhorluck
[Jump back to when you created the reminder](#black-formatter message)
!remind 5H merge https://github.com/psf/black/pull/2525
Your reminder will arrive on <t:1650938826:F>!
There's some code I need to check manually and that coverage drop on PyPy is still super odd, but overall the PR looks OK to me.
blib2to3 iirc, a fork a lib2to3
actually, checking this PR by hand nets me even more questions
gah, why is everything more complicated than it initially appears :)
that's right
I just realized that we have a README stating why we forked blib2to3 (cc @bright glacier since we were talking about this around your blog post). The initial reasons were ```+Reasons for forking:
+- consistent handling of f-strings for users of Python < 3.6.2
+- better ability to debug
+- ability to Cythonize
oh lol that's fantastic
now there's a few more in https://github.com/psf/black/blob/main/src/blib2to3/README
neat
i'm currently using libcst
although it depends on how long they take to fix this bug
don't use blib2to3
LibCST will be 1000x better to work with than blib2to3
it's the most painful parse tree I've ever used
libcst is cool but I kinda wish it was untyped (not that that's relevant to most people, or even means anything)
why??? @silent apex
I'm personally a huge fan of untyped trees with typed layers over them, I like the ease of manipulation and the uniform layers
I guess the f-string reference in the original blib2to3 docs is https://github.com/python/cpython/commit/e8412e684ed741df246e8430f4911b31b0d8be1f
thanks for reminding me of that README Jelle!
speaking of random stuff in the repo, maybe we should get rid of https://github.com/psf/black/tree/main/profiling. It's sometimes annoying when I git grep
Here's your reminder: merge https://github.com/psf/black/pull/2525
[Jump back to when you created the reminder](#black-formatter message)
Is it possible to run black on a file and after that the file to throw errors?
What kind of errors? Black won't parse invalid Python files
Or for Black to destroy the previously valid code?
I have not encountered any error. I was just curious. Sorry if i wasn't clear.
No worries π just wanted to dig deeper
And the other answer (to Black destroying a valid file) is that it's a bug
And yet another answer is that Black naturally can't validate the runtime behavior, so while 1 / 0 is formatted correctly, it will still produce a div by 0 error
Thanks for the explanation
Describe the bug
Using black on 2 different branches of the same code (but with the same config files) I'm getting very different output from black
diff --git a/tasks.py b/tasks.py
index e1303c3..f3f626a 100644
--- a/tasks.py
+++ b/tasks.py
@@ -4,9 +4,7 @@ def scrape_one_twitter(sa_id: int, attempt: int):
impact the rest. Also these are spaced out time to mitigate the rate limiting"""
try:
client = tweepy.Client(
- bearer_token=os.environ["TW...
Description
I was looking for a script to update existing feature branches automatically when introducing black in the main branch, but couldn't find any
To test, you need to blackify your main branch, commit that, switch to a feature branch and then run the script. You'll end up with a copy of your branch blackified and rebased on the main branch
Checklist - did you ...
- [X] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [X] Add new /...
what. <@&831776746206265384> ^
!cban 943359125197324339 we aren't interested in your trolling
:incoming_envelope: :ok_hand: applied ban to @sand mason permanently.
thaaaank you! <3
Describe the bug
PEP8 Whitespace in Expressions and Statements says:
However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted:
This exception is not follo...
Describe the bug
black does not exclude files in git submodules when full filename is passed
To Reproduce
I created an example project with a git submodule to test.
git clone --recurse-submodules git@github.com:janjachnik-dyson/black-submodule-test-super.git
cd black-submodule-test-super
black --check subproject/file.py
The output:
Identified `/tmp/black-submodule-test-super/subproject` as project root containing a .git directory.
Sources to be form...
- Latest version works more
Test: tox -e fuzz
@mint barn Hi, please use #bot-commands for testing the bots. I've removed your messages as to not clutter this channel.
Hi, I was wondering if Black respects when a file uses 2 spaces for indentation instead of 4 spaces, and if it can be configured for using 2 spaces? I have some MicroPython projects that I'd like to use Black on, and I read that 2 spaces should be used instead of the usual 4 spaces to fit more code into memory. I intend to continue to use 4 spaces for my non-MicroPython projects.
Thanks!
Source: https://randomnerdtutorials.com/micropython-programming-basics-esp32-esp8266/
No, we don't support that. Black is meant to create readable code, not save bytes.
If you need to minimize the number of bytes in your program, I'd recommend using a different tool that minifies the code.
Okay thanks for the advice! I'll try to add a minifier as part of the provisioning process so that the code can be written in 4-space-indentation and only minified right before flashing the microcontroller. Thanks again!
Great! Of course there's a lot of other things you can also do in a minifier, like stripping comments and docstrings. Not sure if there's an existing tool for that.
Also, I'd be wary here that you're doing premature optimization. If you don't really need those few extra bytes, you're just complicating your deployment pipeline
this might be interesting for us: https://github.com/ofek/hatch-mypyc
Hatch is going through the PyPA adoption vote at the moment fwiw
I wonder if we can also use cibuildwheel
(If weβre not - didnβt look at Richardβs final automation)
cibuildwheel is awesome
@bright glacier Did you look at using it at all for you wheel building?
The workflow is using it!
Is it not merged yet? cooper-mbp:.github cooper$ grep -R cibuildwheel *
Shows nothing - Was looking before i asked to see how you did it
O right, I have to look at your repo don't I
O, you went envars rather than config - Would you be opposed if I move to config so easier to try build the wheels locally - Just trying to learn
Here's your reminder: can we test CPython 3.11-dev on GHA yet?
[Jump back to when you created the reminder](#black-formatter message)
@neon loom go ahead if you means you get to play with modern packaging and distribution conventions and techniques ^^
Thank you.
O I can maybe get us 3.11 CI if we need it. Or you talking about building wheels?
This is cool to see - same fuzzing (same data samples + size) is 2 seconds quicker in 3.11 vs. 3.10: https://pastebin.com/JAQTyx7Z
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I have a branch already, I just need to retrigger CI on it- errm nevermind
Ahhh ok. Thought so
cython still hasn't made a new release and that blocks some of our deps
yeah cython main supports 3.11-dev, but their release schedule is not fixed or predictable
not sure how I'd hack tox to install a build-time dependency from GitHub
Yeah I donβt think they have many maintainers right ?
Yeah - The poor 1 person
bummer - they have an issue or PR tracking it I take it?
Thanks for this. This is much friendlier to all operating systems.
Only things I think we could do here:
- Should we check that we have a new enough git or are all these arguments been around a long time?
- Lets log black output to a file with the logfile from an option argparse argument
- Maybe also specify you need git + black in your PATH for this to work
- Optionally we could check for that
- Lets type annotate - Again - If you don't have time I can do once we merge ...
@bright glacier or any cibuildwheel gurus - What am I doing wrong here to make cibuildwheel try build a pure python wheel - https://github.com/cooperlees/black-mypyc-wheels (latest commit) when testing locally ...
Do you have (I am prob blind) how you tested locally documented somewhere?
Also, low pri, I'm going to move onto playing with something else now and come back to this
Description
If you have a string that is separated on two lines with a \ and is shorter than the maximum width allowed, it does not get formatted properly by black.
To Reproduce
Create a string on two lines such as:
variable1 = "blahblahblahblah.blahblahblahblahblah." \
"klfdfasdfasdfasblahblahblah"
Run black and you'll get this invalid string:
variable1 = "blahblahblahblah.blahblahblahblahblah." "klfdfasdfasdfasblahblahblah"
**Expecte...
