#black-formatter

1 messages Β· Page 33 of 1

neon loom
#

What web stuffs?

bright glacier
#

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

#

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

neon loom
#

Nice πŸ™‚

flat krakenBOT
#

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.................................................................
bright glacier
#

will check tomorrow

#

!remind 18H Don't forget to clear out some pending reviews once the diff-shades integration is useful again!!!

late dewBOT
#
You're the boss!

Your reminder will arrive on <t:1648153448:F>!

bright glacier
#

hmm I might be in a meeting at that time, but it should be over soon after so it's probably fine.

flat krakenBOT
flat krakenBOT
#

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
  • ...
bright glacier
#

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.

dense jungle
#

I like the second idea, maybe add a separate # preview-output section

errant barn
#

Me too, all for reducing duplication

late dewBOT
bright glacier
#

I guess I'll review the currently open PRs now and then I can look into improving our testing infrastructure after

flat krakenBOT
#

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...
bright glacier
#

Removing multiple unnecessary parenthesizes for for assignment targes is unstable #2952
ah whatever, the typo can live on

bright glacier
# flat kraken

It's this kind of instability I'm worried about with stuff like this

flat krakenBOT
#

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(...
flat krakenBOT
bright glacier
#

Finding lots of bugs in my reviews today lemon_sweat

dense jungle
#

good catch! I was worried about that sort of thing in my reviews but didn't look hard enough

flat krakenBOT
bright glacier
#

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

late dewBOT
#
Of course!

Your reminder will arrive on <t:1648173267:F>!

flat krakenBOT
bright glacier
#

I wonder how many non magic trailing comma instability bugs we're potentially hiding with the second pass hack

winged whale
#

I am setting default formatter to be black formatter

#

How to specify that? Thank you

bright glacier
#

you're missing a comma :p

winged whale
#

Good to go?

bright glacier
#

lemme pull out my vscode config file and see what the right value is

winged whale
#

I dont know why "[python]" is still orange

bright glacier
#
    "[python]": {
        "editor.defaultFormatter": "ms-python.python"
    },
#

this is what I have

dense jungle
#

are you missing a comma on line 7 above

cloud quarry
#

put a comma at the end of line 7

winged whale
#

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

bright glacier
#

did you set

    "python.formatting.provider": "black",

too?

winged whale
#

yellow alert

#

lemme try the implementation

bright glacier
#

it needs to be outside of the python block, i.e. in the main configuration scope

winged whale
#

It works now

#

πŸ‘

bright glacier
#

🌺 lovely!

late dewBOT
flat krakenBOT
#

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...

flat krakenBOT
winged whale
#

Is that a preferred way for you guys to breakdown list comprehension into multiple lines?

errant barn
#

Yeah

winged whale
#

I want to keep it remain single line, can I change the setting?

errant barn
#

You can change line length limits, but I'd maybe just move the comment

winged whale
#

I see. Thank you

errant barn
#

πŸ‘πŸΏ

flat krakenBOT
bright glacier
#

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

nova tinsel
#

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

bright glacier
#

Yea that was the intention, but honestly it's more of a general reminder for "sometime in the future"

#

!remind list

late dewBOT
#
Reminders for ichard26#4772

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?

nova tinsel
#

ok you can !remind edit duration 4276 1m

bright glacier
#

!remind edit duration 4276 1m

late dewBOT
#
I got you.

That reminder has been edited successfully!

nova tinsel
#

sry :) i'll be more careful haha

bright glacier
#

no worries!

long frigate
molten kernel
#

how do i comment out a certain area of text from black formatting?

bright glacier
#

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

molten kernel
#

one sec

#

ah sweet thanks

dense jungle
#

looks like f-string time

bright glacier
#

is this a graphQL query? they are always a pain to write out :)

molten kernel
#

there's no real good way to do it

#

with f-strings i have to double every {}

bright glacier
#

My solution when I last dealt with graphQL was to add placeholder values and use str.replace on 'em -- not exactly pretty lemon_sweat

faint haven
bright glacier
#

I forgot string.Template was a thing πŸ‘€

glacial swan
#

is there a black api or not yet?

bright glacier
#

No ... lemon_sweat

#

We'll get it to it, eventually .. hopefully

#

cute emoji btw!

glacial swan
#

Ok cool

#

thank you

#

I can't wait to use it

#

so I don't need to use my hackyish

#

function anymore

flat krakenBOT
#

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...

flat krakenBOT
#

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
...

flat krakenBOT
#

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...

bright glacier
#

!remind 5H do a systematic review of the current code style and make sure the docs are up to date

late dewBOT
#
Yep.

Your reminder will arrive on <t:1648329582:F>!

bright glacier
#

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

bright glacier
#

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

dense jungle
#

Not sure, can take a look

bright glacier
#

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

late dewBOT
dense jungle
#

turned on this option so we can update branches and get more diff-shades goodness πŸ™‚

dense jungle
bright glacier
#

I forgot we also agreed to use backslashes πŸ˜…

dense jungle
#

hm did we actually commit it? I checked out the commit before your PR but don't see it

dense jungle
#

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."

bright glacier
#

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

bright glacier
#

I'm fine with it too. Wish it was made official but oh well πŸ™‚

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

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...
dense jungle
#

This is pretty bad, would appreciate contributions addressing this

frozen badge
#

the fun moment when you write a message to report a bug and then 2 issues get opened before you can send

dense jungle
#

Either pinning click or making us not use _unicodefun

#

We should be able to do a release today to deploy the fix

fair spade
#

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

fair spade
frozen badge
#

yes

frozen badge
#

they removed something that black uses in the 8.1.0 release which was like 30 minutes ago

fair spade
#

ah ah ah, i started to use black at quite the wrong moment πŸ˜‚

flat krakenBOT
dense jungle
fair spade
#

that's me πŸ˜„

frozen badge
fair spade
#

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 πŸ€”

fair spade
#

Thanks a million @frozen badge

dense jungle
frozen badge
#

(or press . in the repo which should open github.dev/vscode web )

dense jungle
bright glacier
#

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..?

bright glacier
dense jungle
#

hm, seems bad to have a release without wheels

dense jungle
bright glacier
#

it's just a speed up, we'll still have the pure python one obviously

bright glacier
#

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

dense jungle
#

I'm going to try removing the patch entirely as some people on GH were suggesting

bright glacier
#

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

bright glacier
#

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

dense jungle
#

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

bright glacier
#

Yeah having black refuse to work sounds untenable even if it's only on 3.6

flat krakenBOT
dense jungle
#

^ this works locally

bright glacier
#

click, not black but thanks!

dense jungle
#

lol oops

flat krakenBOT
#

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?
dense jungle
#

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?

late dewBOT
#

.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"```
dense jungle
#

yes, just pushed a commit to pin there πŸ™‚

bright glacier
#

seems like a good time to join this server :)

dense jungle
#

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?

dense jungle
#

um 22.3.0

bright glacier
dense jungle
bright glacier
#

those wheels are still the most unreliable part of the release process

dense jungle
#

We were overdue for a release anyway πŸ™‚

bright glacier
dense jungle
#

and you still have to manually run some script for it, right?

bright glacier
#

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

dense jungle
#

OK, let's just do that for this release too then

bright glacier
#

I've been meaning to upstream the mypyc wheel build workflow, but clearly I haven't gotten to it yet lemon_sweat

dense jungle
bright glacier
#

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
toxic stormBOT
bright glacier
#

do we want to wait to release everything at once or upload the wheels later once they're done?

dense jungle
#

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

bright glacier
#

I agree.

dense jungle
#

will prepare the release PR noow

bright glacier
#

52 thumbs up πŸ‘€

flat krakenBOT
bright glacier
#

OK I'll fire the mypyc build workflow now

dense jungle
bright glacier
#

gosh the overthinking part of me is now worrying that the fix doesn't work, ahhhhh

dense jungle
#

that would be embarrassing

flat krakenBOT
#

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...
dense jungle
#

time to eat lunch

bright glacier
#

time to actually drink my french vanilla, I didn't drink it because I was too focused on this madness :p

bright glacier
#

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?

flat krakenBOT
#

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...

bright glacier
long frigate
#

Psst, fully automatic release processes are great https://hypothesis.works/articles/continuous-releases/

dense jungle
bright glacier
#

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

bright glacier
#

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

flat krakenBOT
#

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 ...

dense jungle
bright glacier
#

well that's great ducky_australia

flat krakenBOT
long frigate
neon loom
#

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

long frigate
#

Still doable with github actions!
And you can use the CODEOWNERS file to restrict permissions appropriately.

round ore
#

whats going on everybody

flat krakenBOT
red sedge
#

pipx run build && pipx run twine upload --skip-existing dist/* plz

lament crow
#

re: #2966 he could have had 21.10b0 pinned, just not click

long frigate
red sedge
#

?

dense jungle
#

@lament crow thanks for the support in telling people they have the wrong version of Black installed πŸ™‚

lament crow
#

hah, sure

flat krakenBOT
bright glacier
#
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

dense jungle
#

it's very particular about this

little parrot
#

Is the first param named function in the unit test version?

dense jungle
#

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

late dewBOT
#

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```
little parrot
#

Well there's the issue then

#

It needs to be called func

dense jungle
#

and take *args and **kwargs

bright glacier
#

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)

dense jungle
bright glacier
#
❯ pip list | grep "aiohttp"
aiohttp                       4.0.0a1

unittest_run_loop doesn't exist since aiohttp 4

dense jungle
#

maybe mypy is looking at a different venv?

bright glacier
#

I'm sure I'm missing something obvious but I have no clue what that is

late dewBOT
#

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```
bright glacier
#

turns out it was not even deprecated in 4.0.0a1 Β―_(ツ)_/Β―

#

I guess they keep multiple active branches hence this situation..?

flat krakenBOT
#

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...
flat krakenBOT
#

<!--
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:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. 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 `...
flat krakenBOT
#

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/...
lament crow
#

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...

ripe imp
#

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.

errant barn
#

What's the message? And have you managed to narrow down the cause at all?

ripe imp
#

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.

errant barn
#

Ah, we can't really do much if the file is invalid Python

ripe imp
#

so it can only work for correct syntax?

errant barn
#

Yep, since we rely on Python parsers to do the formatting in the first place

ripe imp
#

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?

errant barn
#

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

ripe imp
#

I did not configure my black , I used default configuration if it matters

errant barn
#

Should be that much easier then

ripe imp
#

okay! Thank you so much!

errant barn
#

You're most welcome!

flat krakenBOT
flat krakenBOT
bright glacier
#

bah, I'm dumb, it's main that's still problematic

dense jungle
dense jungle
#

huh there is no #2980

bright glacier
#

Yay I can remove that override now :)

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

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...

worn badge
#

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?

flat krakenBOT
short forge
#

79 is insanely short
Even 88 is short imho, i use 100

worn badge
#

I thought that was the point of the standard - to standardise and remove opinions

worn badge
#

I missed that, thanks!

#

Just read it - does not really explain why black decided to break with PEP8 rather than trying to change PEP8

olive shell
#

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")

worn badge
#

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

red sedge
#

PEP8 says not to follow it right at the top

#

But ultimately it doesn't matter in the grand scheme of things

lament crow
#

You should watch the talk linked there, not just the linked part tho

#

All of it

teal goblet
#

imo 88 allows for a bit of padding in case your statement goes just over the limit.

#

flake8 actually uses 79 char limit

hearty canopy
#

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.

flat krakenBOT
#

<!--
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:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. 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 `...
silent apex
# flat kraken

I'm guessing they're running a version of 3.11 that doesn't have tomllib

bright glacier
#

I honestly have no idea though, since 3.11a6 is the most recent prerelease and the docs already have tomllib

dense jungle
#

speaking of 3.11, do we have an issue already for except* support?

bright glacier
#

No.

#

!remind list

late dewBOT
#
Reminders for ichard26#4772

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?

silent apex
dense jungle
#

I think we merged it after the alpha was released

silent apex
#

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'
flat krakenBOT
#
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...
flat krakenBOT
#

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...
flat krakenBOT
#

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...
neon loom
#

I think we should accept a tab argument.

errant barn
#

About damn time

neon loom
#

Tabs are the best.

flat krakenBOT
flat krakenBOT
flat krakenBOT
dense jungle
#

lol, great timing here

flat krakenBOT
flat krakenBOT
#

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...
bright glacier
# flat kraken

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

flat krakenBOT
bright glacier
#

that's a very fast review cycle for a formatting PR πŸ‘€

#

I'm still reviewing / editing psf/black#2926

toxic stormBOT
dense jungle
flat krakenBOT
bright glacier
#

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

flat krakenBOT
bright glacier
#
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

dense jungle
#

could just be random

red sedge
bright glacier
#

that would've been a real fun april fools, CI crashes due to a cosmic ray β˜€οΈ

flint cedar
#

anyone know why black sometimes doesn't conform with pep8

dense jungle
flint cedar
#

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

dense jungle
#

Seems like you should read PEP 8 before claiming Black doesn't conform with it πŸ™‚

plain atlas
#
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)
errant barn
#

psf/black#2964

plain atlas
#

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

errant barn
#

meaning we'd release 21.x.x now? :D

flat krakenBOT
#

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...

...

lament crow
flat krakenBOT
#

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...
red sedge
#

!paste

late dewBOT
#

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.

red sedge
#

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)))
        )))        )))
        )))         )))
        )))         )))
        )))        )))
        )))))))))))))
    )
dense jungle
red sedge
#

oh neato

dense jungle
#

but unfortunately it needs specific code for each case

red sedge
#

reminds me of

bright glacier
#

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.

dense jungle
#

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.

bright glacier
#

What's the best way forward for dealing with the click 8.1+ fallout @dense jungle ?

dense jungle
#

Only problem I know of is a CI failure with mypy on our end but that should be fixable

bright glacier
#

I'm thinking to just update our type ignores and add a click>=8.1.0 pin (so everyone's cached hooks get evicted)

bright glacier
flat krakenBOT
#

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/...
bright glacier
#

man, there's a typo in the commit message >.<

naive wren
#

<

#

?

#

:

#

"

#

""

#

?

#

<

bright glacier
#

Please refrain from spamming on topic channels @naive wren .

late dewBOT
#
Affirmative!

Your reminder will arrive on <t:1649188660:F>!

flat krakenBOT
#

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/.

flat krakenBOT
#

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 ...
tired flax
#

hey, is there a way to make black use single quotes instead of double quotes?

tired flax
#

hm

teal goblet
#

black is opinionated like that.

#

You can probably force it on an individual basis by using a " character in your string.

late dewBOT
flat krakenBOT
#

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 ...

flat krakenBOT
flat krakenBOT
#

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?
flat krakenBOT
#

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...
bright glacier
#

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)

flat krakenBOT
#

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 ...

flat krakenBOT
#

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...

bright glacier
#
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

flat krakenBOT
#

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...
sterile mango
#

hi

#

can i help

late dewBOT
#

: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).

spark bone
#

!unmute 764471561343336490

late dewBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @sick patrol.

bright glacier
bright glacier
#

well all of my projects' CI is failing thanks to the click issue, this is quite annoying :)

#

this time it's diff-shades ducky_australia

fast heart
#

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?

errant barn
#

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.

high drift
#

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?

lament crow
#

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

high drift
#

oh i see i see, that worked. thanks!

bright glacier
late dewBOT
#

src/black/__init__.py line 1438

from click import _unicodefun```
bright glacier
#

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

dense jungle
late dewBOT
#

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```
bright glacier
#

ah yeah I have click pinned

#

doesn't bode too well for my memory πŸ˜…

flat krakenBOT
flat krakenBOT
bright glacier
#

I used a spell checker and read over my writing a few times over, hopefully that shows :)

lament crow
#

Huh, I thought there's more projects on diff-shades's list

bright glacier
#

I just stole black-primer's list of projects and added a few of my own projects :p

lament crow
#

I'm sure it's millions of lines of code anyway, just didn't think it would be just 20 or so projects πŸ˜„

bright glacier
#

django and typeshed are responsible for a sizable portion IIRC, along with pillow or pandas?

lament crow
#

isn't pillow mostly written in C

#

or well, Cython

bright glacier
#

I can't remember Β―_(ツ)_/Β―

#

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

bright glacier
#

@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)

dense jungle
#

sure

#

done

bright glacier
#

whee thank you!

dense jungle
#

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

bright glacier
#

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)

stuck vapor
stuck vapor
# stuck vapor 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?

bright glacier
#

currently working on upstreaming the mypyc workflow, hopefully this doesn't crash

bright glacier
#

and I managed to mess twice, once by forgetting a few changes and twice by using the wrong commit message initially

flat krakenBOT
plush zinc
#

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]

flat krakenBOT
mint barn
#

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

dense jungle
flat krakenBOT
modest citrus
#

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.

flat krakenBOT
#

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...
flat krakenBOT
#

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...

bright glacier
#

those are touching different files @errant barn

errant barn
#

...... I'm

bright glacier
#

haha at least you closed Jelle's PR :p

errant barn
#

fk, at least someone is awake

flat krakenBOT
#

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...

bright glacier
errant barn
#

I think I'll sleep now

bright glacier
#

good call :)

flat krakenBOT
lament crow
bright glacier
#

I have no idea Β―_(ツ)_/Β―

silent apex
bright glacier
#

well that's fun.

dense jungle
lament crow
#

ye

silent apex
#

yes

lament crow
#

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

bright glacier
#

ducky_australia yay for os tridiversity

dense jungle
#

ok thanks for checking! someone wants to make another PR? πŸ™‚

lament crow
#

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

unique mulch
#

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

silent apex
#

I believe black does not do things like that for AST safety but I am not 100% sure

lament crow
#

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

lament crow
#

so I feel like doing reformatting in such cases would look weird

silent apex
#

oh I thought I heard it does, woops

#

must have been something else

gilded sable
#

There is a --preview flag or something like that to enable changing the AST I believe

#

not exactly sure

errant barn
gilded sable
#

oh

#

it does have something that changes ast right?

errant barn
#

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

gilded sable
#

okay thanks for the information

gilded sable
errant barn
#

some conversation about an AST toggle in psf/black#2150 though if you're interested!

toxic stormBOT
mint barn
#

black formatter

flat krakenBOT
bright glacier
#

IIRC I was the person that SO answer quoted

dreamy plume
#

what is this about

fast heart
#

How's the progress with this?

#

I plan on having an ast, and wanting to output it using black

dense jungle
#

not much has happened for a while

flat krakenBOT
bright glacier
#

do you mean .*pycache.*? Black uses regexes not globs

tawdry sorrel
#

Hello

flat krakenBOT
#

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...
flat krakenBOT
#

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

  1. Create a sample project directory with folders like src, test
  2. In the project directory create this configuration file pyproject.toml: ``` # Configuration for black pre-commit
    [tool.black]
    exclude = '''
    build.py
    '''
    `...
flat krakenBOT
#

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...

flat krakenBOT
bright glacier
#

!remind list

late dewBOT
#
Reminders for ichard26#4772

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?

bright glacier
#

we don't even run tests on python 3.11-dev

flat krakenBOT
granite stirrup
#

Guys

#

really quick

dense jungle
bright glacier
#

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.

queen apex
#

nice

flint cedar
#

um

#

this channel is for the black formatter

#

but nice language though, looks like C and Python's baby

wraith jacinth
#

this is annoying, how do i make it not annoying

elder tusk
wraith jacinth
#

where do i input that?

silent apex
flat krakenBOT
#

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? -> ...
bright glacier
#

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 lemon_sweat

flat krakenBOT
#

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...
neon loom
#

@bright glacier Wow @ your large ass .yml actions

#

TIL a lot

#

How does the concurrency work?

flat krakenBOT
bright glacier
#

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

neon loom
#

I must be blind. Cheers. That’s good enough then

neon loom
bright glacier
#

I'll be able to explain once I'm back on my laptop, currently on my phone :p

silent apex
#

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)

bright glacier
#

It's exactly that this ... 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

tough saffron
#

probably a silly question, but why does black remove the single empty line here?

if True:
    foo

bar
bright glacier
tough saffron
tough saffron
#

it works fine for me in firefox, but is broken in chrome and edge, hum

bright glacier
#

I'm on chrome Β―_(ツ)_/Β―

tough saffron
#

oh god, what on earth is happening

bright glacier
#

I have no idea. We don't control the playground btw, JosΓ© Padilla does

tough saffron
#

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

bright glacier
#

yup

tough saffron
#

i guess i'll see if they've got an issue for this

dense jungle
#

in inspector it shows that your payload has \r\n newlines and @bright glacier's has \n

tough saffron
#

yeah, I was thinking something like that was the problem. i'll make an issue i guess. i'll mention this

dense jungle
#

let me see if I can repro this with Black directly

#

doesn't repro on the command line

tough saffron
#

aha, thanks! i'll mention this too, then.

dense jungle
mint barn
#

black used to be amv/black for the plugin in vim what is it now?

mint barn
#

wait

#

how do i get the latest version of black (i think it came with PEP 9 or smthn?) for neovim?

glad pilot
#

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?

bright glacier
#

they're not stored anywhere in the built wheel AFAIK

glad pilot
bright glacier
#

the C output is stable though so I could probably generate it locally looking at the build logs

glad pilot
#

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.

bright glacier
#

OK, according to the logs the 22.3.0 wheels used mypy==0.910

glad pilot
#

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...

bright glacier
glad pilot
#

ah! Looks like the class is inheriting __call__ from its superclass. That's probably the test case here...

bright glacier
late dewBOT
#

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```
bright glacier
#

(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)

glad pilot
#

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

bright glacier
#

thank you! @glad pilot

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 πŸ˜„

bright glacier
#

I mean, it's probably just black segfaulting

#

... well hmm mypy is compiled itself but I haven't seen any reports of that

glad pilot
#

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

bright glacier
#

Hmm, how would that work with cibuildwheel?

glad pilot
#

absolutely no idea. πŸ™‚

bright glacier
#

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

glad pilot
#

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.

bright glacier
#

I'm pretty sure mypyc is still technically alpha even though black and mypy are both using it πŸ™‚

glad pilot
#

I believe so, yeah.

stuck vapor
#

Has it already been tried to get black to use mypyc when it's run as a pre-commit hook?

dense jungle
bright glacier
#

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 :/

stuck vapor
#

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'
stuck vapor
#

Do you know if there's a package on PyPI which contains everything necessary to run mypyc?

bright glacier
#

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.

stuck vapor
#

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'
bright glacier
#

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

stuck vapor
#

πŸ€” reckon there's some other way around this then?

bright glacier
#

the cleanest way would probably be to use a shim repository that installs black from pypi or builds black manually, but that seems untenable

stuck vapor
bright glacier
#

python packaging overall doesn't support conditional build time dependencies very well, aiohttp has to deal with this too

dense jungle
#

does mypy itself deal with this when it is used as a pre-commit hook?

bright glacier
#

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.

stuck vapor
# bright glacier https://github.com/psf/black/blob/main/.github/mypyc-requirements.txt

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 πŸ€”

bright glacier
#

that's strange :/

stuck vapor
bright glacier
#

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

flat krakenBOT
#

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

fast heart
#

Black has negatively affected the neatness of the code I write πŸ˜‚

#

I just write dirty code out of laziness and run black

errant barn
#

But with less effort I presume!

mint barn
flat krakenBOT
#

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) :] # ...
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

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...

bright glacier
#

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

late dewBOT
#
You got it!

Your reminder will arrive on <t:1650571237:F>!

dense jungle
#

maybe we should just remove the links for now

flat krakenBOT
flat krakenBOT
vapid citrus
#

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

dense jungle
#

something like set PATH $PATH:/some/new/path

vapid citrus
#

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?

dense jungle
vapid citrus
#

sadly, its not working

#

Wait, it does work in fish shell

flat krakenBOT
flat krakenBOT
#

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...

late dewBOT
ancient shoal
#

Can black-formatter format my casing style?
I used it, and it was great, but I have some very bad, inconsistent naming

errant barn
#

meaning variable naming?

ancient shoal
#

yes

errant barn
#

unfortunately not, that would change the AST, which we try to avoid

ancient shoal
#

I have functions defined in PascalCase, camelCase and snake_case, and lowercase in the project

errant barn
#

but a tool like that would be cool!

ancient shoal
#

thanks, I guess I'll have to do it manually

#

but I have to say, it's really fast and convenient

errant barn
#

or spend 10x the time and automate ;D

ancient shoal
#

showed me syntax I didn't even know existed

errant barn
#

much appreciated πŸ‘πŸΏ

lament crow
#

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

pure wolf
#

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.

dense jungle
pure wolf
#

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.

dense jungle
#

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.

pure wolf
#

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.

flat krakenBOT
#

<!--
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:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. 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 `...
little parrot
flat krakenBOT
#

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...

silent apex
#

^ additionally, you often order code to keep related functions together, and black can't know that

dense jungle
bright glacier
#

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

flat krakenBOT
#

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...

flat krakenBOT
#

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...

flat krakenBOT
#

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 ...

-...

flat krakenBOT
#

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!")
...
upper dirge
#

?

flat krakenBOT
#

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...
static iron
#

Black Lives Matter guys

mint barn
#

🧒

late dewBOT
bright glacier
late dewBOT
#
Yeah okay.

Your reminder will arrive on <t:1650938826:F>!

bright glacier
#

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.

plain atlas
#

what parser does black use

#

a peg parser iirc

silent apex
#

blib2to3 iirc, a fork a lib2to3

bright glacier
#

gah, why is everything more complicated than it initially appears :)

dense jungle
#

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

bright glacier
#

oh lol that's fantastic

dense jungle
plain atlas
#

neat

#

i'm currently using libcst

#

although it depends on how long they take to fix this bug

dense jungle
#

don't use blib2to3

bright glacier
#

LibCST will be 1000x better to work with than blib2to3

dense jungle
#

it's the most painful parse tree I've ever used

silent apex
#

libcst is cool but I kinda wish it was untyped (not that that's relevant to most people, or even means anything)

plain atlas
#

why??? @silent apex

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

dense jungle
bright glacier
#

thanks for reminding me of that README Jelle!

dense jungle
late dewBOT
echo pebble
#

Is it possible to run black on a file and after that the file to throw errors?

errant barn
#

Or for Black to destroy the previously valid code?

echo pebble
errant barn
#

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

echo pebble
#

Thanks for the explanation

flat krakenBOT
#

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...
flat krakenBOT
#

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 /...
errant barn
#

what. <@&831776746206265384> ^

molten hare
#

!cban 943359125197324339 we aren't interested in your trolling

late dewBOT
#

:incoming_envelope: :ok_hand: applied ban to @sand mason permanently.

errant barn
#

thaaaank you! <3

flat krakenBOT
#

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...

flat krakenBOT
#

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...
flat krakenBOT
flat krakenBOT
silent apex
#

@mint barn Hi, please use #bot-commands for testing the bots. I've removed your messages as to not clutter this channel.

swift mauve
#

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/

dense jungle
#

If you need to minimize the number of bytes in your program, I'd recommend using a different tool that minifies the code.

swift mauve
dense jungle
#

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

dense jungle
neon loom
#

Hatch is going through the PyPA adoption vote at the moment fwiw

neon loom
#

I wonder if we can also use cibuildwheel

#

(If we’re not - didn’t look at Richard’s final automation)

dense jungle
#

cibuildwheel is awesome

neon loom
#

@bright glacier Did you look at using it at all for you wheel building?

bright glacier
#

The workflow is using it!

neon loom
#

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

late dewBOT
#
It has arrived!

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)

bright glacier
#

@neon loom go ahead if you means you get to play with modern packaging and distribution conventions and techniques ^^

neon loom
#

Thank you.

neon loom
# late dew

O I can maybe get us 3.11 CI if we need it. Or you talking about building wheels?

bright glacier
#

I have a branch already, I just need to retrigger CI on it- errm nevermind

neon loom
#

Ahhh ok. Thought so

bright glacier
#

cython still hasn't made a new release and that blocks some of our deps

neon loom
#

Is it merged?

#

Just not released?

bright glacier
#

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

neon loom
bright glacier
#

It looks like scoder is still maintaining it

#

mypyc is also broken on 3.11

neon loom
neon loom
flat krakenBOT
#

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 ...
neon loom
#

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

flat krakenBOT
#

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...