#black-formatter

1 messages ยท Page 2 of 1

lament crow
#

does normal Black (not blackd) preserve CRLF? ๐Ÿค”

lament crow
#

huh, it in fact does, I have not expected that

pastel breach
#

Why would you expect that Black won't preserve CRLF?

lament crow
#

I thought that a part of Black's style would be to enforce LF

neon loom
#

I am the king of finding weird bugs

#

GitHub not so friendly on slow high latency links

neon loom
#

Just wonder if this could break any IDEs etc. using blackd

lament crow
neon loom
#

Yeah, that was misleading. If you're on windows, and you make a text file with CRLF python can support it and a developers editor might need the CRLF so I thought we (black) wanted to preserve that

lament crow
#

I'm not really suggesting that Black should normalize line endings to LF, though I am surprised that it doesn't do that already ๐Ÿ˜„

lament crow
neon loom
#

We wanted to break less so I thought (and I could be wrong / not remember) that we wanted to preserve CRLF for Windows users ... but happy to be wrong

errant barn
#

git takes care of that, so dev on Windows would be a bit awkward if Black didn't preserve them

neon loom
#

I'd prefer we normalized to \n as a POSIX Unix/Linux guy

#

Yeah, I have 0 Windows skills/knowledge

lament crow
#

So after formatting, it wouldn't really matter

bright glacier
#

Regardless, I find it odd how black preserves CR but blackd does not

errant barn
#

git status will be off I think

lament crow
bright glacier
#

Makes me question the PR since it feels like it's overcomplicating something

lament crow
#

As I said, I was just surprised that Black doesn't normalize to LF

lament crow
bright glacier
#

Probably, but I would like to figure out why before accepting the PR

errant barn
lament crow
#

is this about git status showing the file as having unstaged changes even when the only change is CRLF->LF and only after you git add it, git starts properly to ignore it while not actually staging the file since there's nothing to stage? :

#

autocrlf is kinda funky like that, just didn't feel like it's that big an issue

#

but yeah, fair point :P

neon loom
bright glacier
#

I can take over and get it merged now it's blocking work.

neon loom
#

So I can't ignore it via the pyproject.toml pytest settings cause it's in aiohttp?

bright glacier
#

you can, but we also have to mitigate it in blackd's source code to not blow up when the decorator is removed from aiohttp

neon loom
#

Rightio โ€ฆ seems a good path and saves us hard setting >= 4.0 right away and be ready for it

#

Iโ€™ll try look at it if you gone beat me. I had some time waiting for connecting flight home and now out of time.

bright glacier
#

I'm preparing a PR right now

#

annoyingly both mypy and flake8 really hate the changes I initially suggested

neon loom
#

I wish aiohttp did more minor release more often

#

So many changes on GitHub vs PyPI version

bright glacier
#

I wished they released more often too

#

there are so many deprecation warnings, gah, it was confusing to test my patch because I was running into upstream deprecation warnings about deprecated loop arguments

#

it works though, will submit the PR now!

neon loom
#

Awesome.

flat krakenBOT
#

Description

This is deprecated since aiohttp 4.0. If it doesn't exist just define a no-op decorator that does nothing (after the other aiohttp imports though!). By doing this, it's safe to ignore the DeprecationWarning without needing to require the latest aiohttp once they remove @middleware.

Resolves GH-3176. Closes GH-3198.

Checklist - did you ...

  • [x] Add a CHANGELOG entry if necessary? -> n/a
  • [x] Add / update tests if necessary?
  • [x] Add new / update outda...
austere lava
#

it's starting to look nice! ๐Ÿ™‚

neon loom
#

Cool

flat krakenBOT
flat krakenBOT
#

Describe the style change

Original code:

function_call(
    (
        " lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor"
        " incididunt ut labore et dolore magna aliqua Ut enim ad minim"
    ),
    " veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo",
)

Examples in the current Black preview style

black --preview removes the parens since they are "not necessary":

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

Description

Fixes #3261.

When LL[0] is an atom string, we need to check the atom node's siblings instead of LL[0] itself, e.g.:

dictsetmaker
  atom
    STRING '"This is a really long string that can\'t be expected to fit in one line and is used as a nested dict\'s key"'
  /atom
  COLON ':'
  atom
    LSQB ' ' '['
    listmaker
      STRING '"value"'
      COMMA ','
      STRING ' ' '"value"'
    /listmaker
    RSQB ']'
  /atom
  COMMA ','
/...
slow ibex
austere lava
#

I'll try and do something about it

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
flat krakenBOT
flat krakenBOT
clever peak
#

@bright glacier sorry for the ping, can you let me know once you have some free time?

glacial drum
bright glacier
clever peak
clever peak
bright glacier
clever peak
flat krakenBOT
#

Describe the bug

File failed to format. Both the file and diff are attached to this message.

Error present in both newest version of black (used pip install --upgrade black to make sure) and [online formatter] (https://black.vercel.app/?version=main).

Environment

Operating system: Linux (xubuntu 22.04 64bits)
Python version: 3.10.4
black.__version__ == '22.8.0'

The resulting error

running black main.py produces the following error:

error: cannot fo...
bright glacier
clever peak
pastel breach
#

how to make black not fail in pre-commit when it modifies?

glacial drum
#

pre-commit only runs against the code in the staging area. When black (or any pre-commit hook that auto-fixes your code) fixes your code, you must then add that code to the staging area (using git add), then the next time you try to commit it will pass.

pastel breach
#

hmm

#

Maybe I need a pre-precommit

#

That runs isort and black

#

Before staging

errant barn
cosmic topaz
#

Hi. I've poked around the black codebase a few times. I'm writing a formatter for Jinja strings and one of the goals is to follow black's style for any of the pythonic bits. I can't use just black, because there is plenty of jinja-specific syntax I'm working with.

So, my question: how does black decide where to add new lines? Is there a particular place in the codebase I can look at to see more about line wrapping?

austere lava
glossy olive
#

@cosmic topaz

cosmic topaz
flat krakenBOT
flat krakenBOT
tawny heron
#

How do I make black to ignore a file. Any prefix like something I need to put on top the file for that??

tawny heron
#

using #fmt off in vscode, resolved

flat krakenBOT
#

Describe the bug

Black in some cases put the wrong parts on separate lines when having a trailing comma.

For example this:

assert foo(1, 2, 3,)[
    0
] == {'bar': 'baz'}

Expected result was something like:

assert foo( 
   1,
   2,
   3,
)[0] == {'bar': 'baz'}

To Reproduce

Minimal example:

a = [1,][2]()
b = [1,][2](3)

Expected:

a = [
    1,
][2]()
b = [
    1,
][2](3)

Actual result...

lament crow
#

Interesting

flat krakenBOT
#

It seems that a combination of incorrect formatting and the presence of an incomplete f-string produces a parsing error. The interesting issue is that the error is not raise when the formatting is correct.

I think this is best explained by an example.

This raises a parsing error ("cannot use --safe with this file; failed to parse source file."):

non_capitalised = {
    c: lowercase_map[c]
    for c in columns if (c.lower() in lowercase_map and c not in expected_cases)
}
if...
cyan brook
#

Minor question about stability policy (https://black.readthedocs.io/en/stable/the_black_code_style/index.html). It mentions the following.

"If code has been formatted with Black, it will remain unchanged when formatted with the same options using any other release in the same calendar year.
This means projects can safely use black ~= 22.0 without worrying about formatting changes disrupting their project in 2022."

My understanding of ~= 22.0 is that it allows only the patch updates as >=22.0 <22.1
In order to allow even minor releases during the year, should the dependency be ^=22.0, that is >=22.0 <23.0?

bright glacier
late dewBOT
#
**PEP 440 - Version Identification and Dependency Specification**
Status

Final

Created

18-Mar-2013

Type

Standards Track

bright glacier
#
>>> from packaging.specifiers import SpecifierSet
>>> s = SpecifierSet("~= 22.0")
>>> s.contains("22.0")
True
>>> s.contains("22.1")
True
>>> s.contains("22.0.1")
True
>>> s.contains("22.9")
True
>>> s.contains("23.0")
False

yup.

lament crow
#

yeah, more specifically it replaces last digit with a wildcard so i.e. ~= 22.0.0 would mean >=22.0.0, == 22.0.* while ~= 22.0 means >=22.0, == 22.*

neon loom
#

The two messages there seems a little spammy

bright glacier
#

I don't really mind to be honest

#

If we had to remove one, I'd kill the new commit one though

flat krakenBOT
bright glacier
#

@half meteor and whoever is following this channel, I had around 25 minutes to spare tonight hence the activity. I'm not sure when I'll have more time, but I promise I haven't forgotten your work / PRs!

lament crow
#

how dare you have [life stuff to deal with]

#

seriously though, you're doing great job with this project, it's fine to have other things to do ๐Ÿ˜„

#

especially in entirely voluntary project

half meteor
flat krakenBOT
#

Description

These two paragraphs were tucked away at the end of the section, after the diversion on backslashes. I nearly missed the first paragraph and opened a nonsense issue, and I think the second belongs higher up with it too.

Checklist - did you ...

  • [x] Add a CHANGELOG entry if necessary?
    A changelog entry is unnecessary, I believe.
  • [x] Add / update tests if necessary?
    N/A
  • [x] Add new / update outdated documentation?
    Yes
flat krakenBOT
#

Black documentation used to contain a section on how to use Black with PyCharm via a file watcher utility.

Now there is no mention of this option of using Black, only though a third party plugin AND some more dependencies.
There might be reasons why I don't want or can not install other dependencies, for example aiohttp or PyCharm extensions that is required for Black[d]

Describe the solution you'd like
Add a documentation section on how to use Black with PyCharm file...

proven sphinx
#

Hi, I came here after reading that sublack is no longer being maintained, however it is still the recommended sublime plugin for black. Does anyone here have a recommendation for a sublime plug-in for black that is being maintained?

lament crow
#

You can use SublimeLSP

#

And then use pylsp with that

#

Or you know, you could just continue using sublack because it works just fine

#

Unless there's something in particular that doesn't work for you and you actually need an alternative

#

I'm using sublack right now and personally don't see why I would even need the plugin to be maintained, it serves my purposes and Sublime Text's plugin APIs are quite unlikely to change in incompatible ways in this decade.

lament crow
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Bug description

Changing line lengths is not reversible because Black adds a trailing comma to some argument lists.

To Reproduce

def some_fn(*args):
    pass
some_fn(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)

Reformatting with --line-len=20 results in

def some_fn(*args):
    pass


some_fn(
    1,
    2,
    3,
    ...,
   20,
)

Unfortunately, due to the trailing comma after the 20 that wasn't there before, re-black-ing ...

flat krakenBOT
flat krakenBOT
#

Description

This shouldn't be necessary, but in practice macOS also requires freeze_support() so let's play it safe and always call it when sys.frozen is truthy. Only a tiny sliver of users will be using these PyInstaller executables and the start-up performance is already terrible as the executable unzips itself on the fly anyway.

Fixes #3250.

Checklist - did you ...

  • [x] Add a CHANGELOG entry if necessary?
  • [x] Add / update tests if necessary?
  • [x] Add new / update ...
bright glacier
#

Currently working on getting mypyc wheels to build on 3.11 via CIBW

bright glacier
#

Mildly annoyed that myst-parser still hasn't published a new release with docutils 0.19 support

bright glacier
#

OK attempt two at writing a status update on 22.9.0 (because I accidentally pressed Ctrl-R while writing it):

  • I'll review the hatchling PR and then the "autodetect target-version using project.python-requires" PR soon
  • I will probably not review the blackd PR anytime soon as I honestly do not care, feel free to merge it without my review
  • I filed PRs to both fix the broken macOS executables and start building mypyc wheels for CPython 3.11
  • I'm planning to resolve the merge conflicts in https://github.com/psf/black/pull/2996 and land it if no one objects

Regarding the hatchling PR, it already looks good, but I'll take one more look to hopefully make sure it's alright. I'm a little worried for the downstream redistributors of Black that aren't using PEP 517, but I don't know how to reach out to warn them in the first place :/

flat krakenBOT
#

Description

Bumps cibuildwheel from 2.8.1 to 2.10.0 which has 3.11 building enabled by default. Unfortunately mypyc errors out on 3.11:

src/black/files.py:29:9: error: Name "tomllib" already defined (by an import)  [no-redef]

... so we have to also hide the fallback import of tomli on older 3.11 alphas from mypy[c].

Closes #3224.

Checklist - did you ...

  • [x] Add a CHANGELOG entry if necessary?
  • [x] Add / update tests if necessary?
  • [x] Add new / update...
lament crow
#

out of pure curiosity, do you still have plans to move to nox (since you'll be dropping 3.6 support in this release)

bright glacier
#

nope.

lament crow
#

not at all or just not now?

bright glacier
#

if we're going to change our project automation, it's probably towards hatch

lament crow
#

I guess that makes sense

#

๐Ÿ˜„

bright glacier
#

not that that's going to happen anytime soon as I'm the only one working on developer UX and well, I'm pretty busy

lament crow
#

but yeah, this is just pure curiosity since you were thinking of doing that some time ago and got blocked by the 3.6 drop by nox

faint haven
# flat kraken

Not sure if i'm doing something wrong, but trying the example in black it seems that it isn't formatted at all:

https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADzAHhdAD2IimZxl1N_WmufDs0LpCJTlr0_63xUyw1aWuhyul0IGehj5zH44s9w8q-CZ64PJzAzvgwEYl0U_usCV6jOPlBMQVm6jx7zj0NUJfqWM2pVYKf7x8JwWCc5eMEcx7GjybPRr6VpqZ5OnkMZC7Daks6OzrB80dFoAADWtQBipOBpnQABlAH0AQAA_0IEcLHEZ_sCAAAAAARZWg==

(I tried it with a couple different combinations of settings and none seemed to do anything)

Playground for Black, the uncompromising Python code formatter.

lament crow
#

The above is a document about future style

#

You actually can't parenthesize context managers before 3.9 (provisionally) and 3.10 (stable)

#

there were plans to use \ for splitting them on lower versions but I'm not sure that's still planned considering newer versions support splitting it without backslashes

#

but yeah, all of this is about future style, afaik it hasn't been implemented yet into the --preview style either

faint haven
#

Ahh, that makes sense, thanks

winged whale
#

Hello. May I ask how to use hotkey to auto lint with black?
I set it up while ago, but I forgot to mark up the steps of how to make it

bright glacier
#

What editor / ide are you using?

winged whale
bright glacier
#

I don't have access to an instance of Visual Studio Code so I can't really provide anything more specific than that right now, sorry!

winged whale
bright glacier
#

That looks good assuming black is available in the active python environment

#

IIRC the shortcut is Ctrl-I or Ctrl-Shift-I

winged whale
#

Is that the expected behavior of linting? not used while ago.
I expect it should correct all of it automatically

bright glacier
#

That's not black at all. Sorry I didn't realize the misunderstanding earlier.

#

Black is not a linter, it's an autoformatter so it simply reformats code (changing whitespace, linebreaks, parentheses, etc.)

winged whale
#

yes

bright glacier
#

Pylance and flake8 are linters, but they don't have any autofix functionality as far as I know

#

?

winged whale
#

The first two was already enabled but it is not work

#

And now I enabled the third one

bright glacier
#

what happens when you press shift-alt-F ?

winged whale
#

And then select black, no response

bright glacier
#

yeaaa, your python code is invalid, black won't be able to format that

#

can't remember if the python extension emits an error if black fails

#

ah it does not

winged whale
bright glacier
#

What do you mean by linting? Black is never going to raise any warnings or errors in the messages tab, it's not a linter.

#

(autopep8 is also not a linter FTR)

#

I would be incredibly surprised if autopep8 has error recover and can format only the parts of a file that are syntactically valid, ignoring the broken bits

winged whale
bright glacier
#

I know that. What you're saying isn't making sense to me. What do you mean by "vscode still lints correct lines before" ?

bright glacier
winged whale
#

Yes. I got it now. That's a very clear guidance. Thank you!

#

That's my summary

bright glacier
#

That's not really accurate either. While some warnings / errors linters raise may be fixed by autoformatters (usually ones about style, see the F prefixed flake8 errors), that's more a happy side-effect / accident

#

linters and formatters are very different, they can have overlapping goals (deal with code issues, whatever they may be) but their approaches are very different and so are their domains

#

linters usually only detect and warn, there are probably some linters with autofix functionality but flake8 is definitely not one of them. anyway linters also go beyond just code style, they might warn on unsafe code (e.g. bandit), type issues, overly complex code, etc.

#

formatters are laser focused on the code formatting / style, they shouldn't affect the logic or execution of the code

winged whale
#

not quiet understand. But you did a very good job of explaining the concept. I think I have 90% understanding now, thanks ๐Ÿ‘

bright glacier
#

(tools that automatically change the logic or execution of a program might be called optimizers or refactoring tools depending on what they do, but not formatters AFAIK)

flat krakenBOT
neon loom
#

@bright glacier I can't get those ARM wheels to download

#
crl-m1:tmp cooper$ wget https://github.com/ichard26/black-mypyc-wheels/suites/8342284497/artifacts/367142266
--2022-09-18 16:10:55--  https://github.com/ichard26/black-mypyc-wheels/suites/8342284497/artifacts/367142266
Resolving github.com (github.com)... 64:ff9b::c01e:ff71, 192.30.255.113
Connecting to github.com (github.com)|64:ff9b::c01e:ff71|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2022-09-18 16:10:55 ERROR 404: Not Found.
#

Tried safari too - Will try chrome

#

Ok - seems chrome worked. lol

bright glacier
#

lol wat

#

I would've thought the download link expired, not that it only works on chrome ๐Ÿฅด

neon loom
#

3.10 wheel worked

#

I don't have 3.11 installed on my M1

pastel breach
#

Can we scope # fmt: off such that it re-enables automatically after coming out of scope?

#

Or is there like a fmt_off decorator to mark functions that should not be formatted?

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

Is your feature request related to a problem? Please describe.

I'm trying to setup a GitHub Action that runs Black on a project that includes *.py and *.ipynb files, but the default action does not include the Jupyter extra. I followed the integration described in this piece of documentation but the option to include the Jupyter extra (black[jupyter]) is not available.

Describe the solution you'd like
...

flat krakenBOT
#

Description

This PR fixes #2567, #3184, #2985, #2882, #2232, #2140, #1817, #569. Previously Black produces invalid code because the # fmt: on is used on a different block level.

While Black requires # fmt: off and # fmt: on to be used at the same block level, incorrect usage shouldn't cause crashes.

The formatting behavior this PR introduces is, the code below the initial # fmt: off level will be turned off for formatting, when # fmt: on is used on a dif...

lament crow
#

damn

#

2/3rds of fmt issues closed ๐Ÿ˜„

#

at least the triaged ones

bright glacier
#

oh gosh, it's september 22 already ๐Ÿ‘€

#

I really need to finalize the most critical parts of this release this weekend (I should be free ๐Ÿคž )

glacial swan
#

(please ping response)
is there an official black formatting api, for me to use instead or still a weird workaround or not right now?

bright glacier
glacial swan
#

Actually I have a weird question

#

so I run it the util in run_in_executor

#

right now, but can I do this in an asyncio.create_thread()?

flat krakenBOT
dense jungle
#

it's possible you'll run into issues if you try to format multiple files at once

#

if black's multiprocessing interacts poorly with asyncio

glacial swan
#

sip Sounds like we should test this tbh

flat krakenBOT
glacial swan
#

await asyncio.to_thread()

#

Oh okay cool

#

yep

dense jungle
#

@bright glacier ```jelle@mbpt-root pyinstaller % git grep freeze_support
PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py:def _freeze_support():
PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py:multiprocessing.freeze_support = spawn.freeze_support = _freeze_support

#

they monkeypatch it ๐Ÿ˜„

#

so it does indeed do something on macos

bright glacier
#

so the CPython docs aren't wrong , but just useless a lot of the time, sigh.

#

I guess if you used cx_freeze, the docs would be right since it doesn't even support macOS or Linux

dense jungle
#

maybe add a comment to the code about this monkeypatching and then we can land your PR

flat krakenBOT
flat krakenBOT
flat krakenBOT
lament crow
#

whooooo

austere lava
#

Wow

hollow gazelle
#

why black formater why not white formater

silent apex
#

why not?

#

the name is a play on the quote "any color you like, so long as it's black" by henry ford (paraphrasing)

flat krakenBOT
#

Description

Just a very small quality-of-life change. Clicking the big Black logo in the README will now take you to the documentation page, as opposed to just taking you to the logo file.

Checklist - did you ...

  • [ ] Add a CHANGELOG entry if necessary?
  • [ ] Add / update tests if necessary?
  • [ ] Add new / update outdated documentation?
flat krakenBOT
bright glacier
#

i finally did a thing

#

I will admit I'm nervous changing something as low-level as the build backend, but the Python packaging ecosystem is reasonably modern now, hopefully?

flat krakenBOT
bright glacier
#

@austere lava @red sedge if you want to, you can now clean up our asyncio code now that Black requires Python 3.7+

flat krakenBOT
bright glacier
#

pyupgrade likes to add optimizations re. comprehensions ยฏ_(ใƒ„)_/ยฏ

dense jungle
#

I'm always a bit leery about those because I feel like the listcomp version is likely to be usually faster in practice. But I think mypyc compiles genexps as listcomps anyway ๐Ÿ™‚

bright glacier
#

Yup, mypyc does convert genexprs to listcomps anyway :)

bright glacier
#

The timing on my freeze_support() PR haha ๐Ÿ˜„

dense jungle
#

did I just beat you on the merge?

bright glacier
#

yup, I was confused at why it did nothing

dense jungle
#

๐Ÿ˜„

flat krakenBOT
bright glacier
#

holy crap, I did not expect so many upvotes on psf/black#3214

toxic stormBOT
flat krakenBOT
flat krakenBOT
bright glacier
#

Yes?

bright glacier
dense jungle
#

ModuleNotFoundError: No module named 'hatchling'

bright glacier
#

Not sure why it's not happening on Linux

#

I also swear the Hatchling PR was working before I merged it ducky_australia

#

According to the logs, it's just refusing to install the build-system dependencies before calling prepare_metadata_for_build_wheel?

#

like it's skipping straight to "preparing metadata ..." for some reason

bright glacier
#

I give up, I have other work to do.

flat krakenBOT
#

Description

I believe most users would not want to run black[jupyter] on files in .ipynb_checkpoints/.

This PR adds .ipynb_checkpoints/ to DEFAULT_EXCLUDES in src/black/const.py

I did a quick issue search and couldn't see if a PR like this is outside of scope or has been rejected in the past (https://github.com/psf/black/issues?q=is%3Aissue+ipynb_checkpoints)

Checklist - did you ...

  • [ ] Add a CHANGELOG entry if necessary?
  • [ ] Add / update tests if neces...
rapid yoke
#

why is black's output different for:

import os

import requests
```and```py
import os


import requests

shouldnt one of the them be changed to the other since they are the same (pretty much) or does black allow the user to choose the amount of lines they want?

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

I was working on a project that is only intended to run on Python 3.10. However, the black configuration incorrectly listed multiple target versions because I copied the file from a different project.

When I tried to format a file with a match statement, the error was

error: cannot format foo.py: Cannot parse: 2:6: match bar:

I was initially confused as I knew that black had added Python 3.10 support. Then I...

flat krakenBOT
flat krakenBOT
elder tusk
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

Adds a new CLI option to skip the first line of source code while formatting. To enable use the -x/--skip-source-first-line flag. The skipped line will be retained in the output. The option is also available for blackd.

Closes #3214

Checklist - did you ...

  • [X] Add an entry in CHANGES.md if necessary?
  • [X] Add / update tests if necessary?
  • [X] Add new / update outdated documentation?
#

Description

Adds a new CLI option to skip the first line of source code while formatting. To enable use the -x/--skip-source-first-line flag. The skipped line will be retained in the output. The option is also available for blackd.

Closes #3214

Checklist - did you ...

  • [X] Add an entry in CHANGES.md if necessary?
  • [X] Add / update tests if necessary?
  • [X] Add new / update outdated documentation?
flat krakenBOT
flat krakenBOT
#

Describe the style change

Black 22.8.0 makes typing hints in Python โ‰ฅ 3.10 harder to read by line breaking on the pipe (type union) operator without any apparent reason.

Examples in the current Black style

I'm writing a FastAPI application:

from fastapi import APIRouter, Query

router = APIRouter(prefix="/black", tags=["black"])


@router.get("/foo")
async def foo(
    param1: str
    | None = Query(
        default=None, title="A parameter", descript...
flat krakenBOT
#

Description

Enforce empty lines before classes/functions with leading comments:

  • Fixes #246
  • Fixes #3300

EmptyLineTracker works on lines that haven't been split yet. When sticky leading comment is used before class/def lines, the tracker must look behind the possible comment lines. So I introduced a new LinesBlock class to keep track of those states.

Checklist - did you ...

  • [x] Add an entry in CHANGES.md if necessary?
  • [x] Add / update tests if ...
flat krakenBOT
sudden rampart
bright glacier
#

I always wanted to work on that, but I've never had the time to commit to another major project like that.

plain atlas
#

welp.

#

i don't understand this change

#
    @property
    def cog(self) -> Optional[Cog]:
-       """Optional[:class:`.Guild`]: Returns the guild associated with this context's command. Returns ``None`` if not available."""
+       """Optional[:class:`.Cog`]: Returns the cog associated with this context's command. Returns ``None`` if it does not exist.
+       """
#

imo it does not make the code easier to read

#

i might be in the minority but i really dislike docstring touching

#

like

#

it arguably looks worse having the """ all alone on a line with the entire docstring before that

half meteor
flat krakenBOT
#

When a docstring is formatted using markdown, an extra space at the end means that the next line is not to be wrapped. (pydoc3 uses markdown). Unfortunately, black removes the extra space, which causes markdown renders to not do what they are supposed to.

Example code that gets miss rendered. Note: I am using a _ to denote a space at the end of the line.
Original

def boo():
    """Halloween.

    This is not supposed to be wrapped._ 
    New text
    """

After ...

flat krakenBOT
flat krakenBOT
plain atlas
dense jungle
plain atlas
#

yeah, psf/black#3044

toxic stormBOT
plain atlas
#

although it seems like a bugfix that affects everyone else who wasn't affected by the bug

plain atlas
#

was a change between 22.3.0 and 22.6.0

#

that pins it down to these

#

it looks to be this one:

Docstring quotes are no longer moved if it would violate the line length limit (#3044)

which reading it again sounds right, but i can see a different way it could be worded

#

Docstring quotes that would violate the line length limit now follow behind a single-line docstring

#

i can also see that it's an awkward format and that sometimes that second line behind a docstring matters a lot

#

the issue i have with this fix is that there's two other ways that aren't touched at all

#
# leaves this as-is
"""
Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has."""

# leaves this as-is too
"""
Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has.
"""
``````py
# but provide this...
"""Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has."""
# ...and it turns into this:
"""Dict[:class:`str`, :class:`Flag`]: A mapping of flag name to flag object this converter has.
"""
half meteor
#

+1 to not moving the trailing quotes in the last example
especially given it's not moved in the first example above

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

As a new user of black, I installed the black package from my distribution to try it out. After that, I wanted to integrate it into vim. I set up the plugin, but discovered that the plugin requires building a virtualenv within which to install black. Using a virtualenv is undesirable to me for the following reasons:

  • I already have black installed; there should be no need to install it again.
  • The virtualenv adds clut...
#

Provide a configuration parameter to the Vim plugin which will allow the plugin to skip setting up a virtualenv. This is useful when there is a system installation of black (e.g. from a Linux distribution) which the user prefers to use.

Using a virtualenv remains the default.

Description

I have several reasons why using a virtualenv is undesirable to me. I have listed them in the following feature request.
Fixes: https://github.com/psf/black/issues/3308

Checklist - did yo...

flat krakenBOT
#

Describe the style change

The main use of semicolons in Jupyter Notebooks is to hide the output of some function calls.

Examples in the current Black style

import seaborn as sns


ax = sns.scatterplot(
    x=df["tenure"],
    y=residuals,
)
ax.set_ylabel("Residual")

After executing a cell with the code above, 2 things are outputted:

  1. Text(0, 0.5, 'Residual')
  2. The graph itself.

![image](https://user-images.githubusercontent.com/380158...

dense jungle
#

^ I feel like we already did something about this?

#

in any case let me add a jupyter label

fading reef
#

hello, anyone can help to setup black in my vscode?

flat krakenBOT
flat krakenBOT
bright glacier
#

I was going to approve that, but sure that also works :)

#

I really hope the release CD doesn't break

dense jungle
#

although I might release typing-extensions first

bright glacier
#

I've fixed so many issues I feel like it shouldn't find a way to break by now, but automatic C compilation can be pretty thorny.

flat krakenBOT
dense jungle
#

here we go

bright glacier
#

well the mypyc jobs haven't immediately crashed, that's a good sign

dense jungle
#

how long are they expected to take?

bright glacier
dense jungle
bright glacier
#

yup I just noticed that

#

I'll fix that later today

dense jungle
#

thanks, the universal2 workflow also uploads x86_64 wheels

bright glacier
#

does hatch not support cross-compilation?

dense jungle
bright glacier
#

@tender drift hi does hatch support cross-compilation to macOS ARM and universal2?

#

I'm going to feel like a massive idiot if hatch does not.

dense jungle
#

hm I can't find docs that say "macos_arch" does something

tender drift
#

@bright glacier hatch-mypyc just calls setuptools

bright glacier
#

ah okay so it should work, I guess the cross-platform configuration is being dropped somewhere

tender drift
#

so yes?

#

I haven't tried new CIBW recently

bright glacier
#

perhaps using build as the frontend instead of pip could fix this?

#

I'll need to take a look at the CIBW code to have any clue though

#

I have to go now, but I'll take a look when I have more time

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

lol we actually did build amd64 wheels, they're just labeled x86_64

bright glacier
#

yup

#

I'm writing a reply with that

dense jungle
#

I'll just delete the macos wheels from pypi until we sort this out

bright glacier
#

sounds good

dense jungle
#

done

flat krakenBOT
#

Description

The https://github.com/psf/black/releases/tag/22.10.0 removed runtime support for EOL Python 3.6. ๐Ÿš€

We can remove a few old checks and config.

Updating the mypy config means we can remove a couple of # type: ignore.

Checklist - did you ...

  • [n/a?] Add an entry in CHANGES.md if necessary?
  • [n/a] Add / update tests if necessary?
  • [n/a] Add new / update outdated documentation?
flat krakenBOT
#

First of all currently it is not possible to use straight sphinx-build command to build documentation out of source tree

+ /usr/bin/sphinx-build -j48 -n -T -b man docs build/sphinx/man
Running Sphinx v5.2.3
/usr/lib/python3.8/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.17.1-unknown is an invalid version and will not be supported in a future release
  warnings.warn(

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-p...
lament crow
#

Oh man, this is the infamous packaging guy, isn't he

#

Sure is

bright glacier
#

yeaa, at least this issue is not unreasonable

#

I generally don't like sys.path shenanigans but for docs, it's a lot more acceptable

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

Using version specifier in GitHub Action fails. I believe this is because the stable branch has not been updated.

To Reproduce

Add the following GitHub Action to your repo:

name: Lint

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: psf/black@stable
        with:
          options: "--check --verbose --skip-magic-trailing-comma"
          version: "~= 22.0"

...

flat krakenBOT
#

I'm looking for a way to remove the trailing comma check. When creating lists and dictionaries, the trailing comma as a style choice should be optional NOT required.

I've been leveraging the TOML configuration file as part of the Super-Linter project and Black doesn't seem to honor any of the configuration I am trying to enforce.

Describe the solution you'd like

I'd like a descriptive document around what syntax is expected for the TOML file.

**Describe alternatives you've con...

bright glacier
#

The stable branch is automated, but since release CD failed, it wasn't updated. Perhaps it is indeed better to only gate it on the sdist + pure wheel job

flat krakenBOT
flat krakenBOT
#

Describe the bug

When I try to use vim to run Black, I get the following message:

Error detected while processing function black#Black:
line 10:
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 143 in Black
TypeError: __init__(): got an unexpected keyword argument 'preview'
Press ENTER or type command to continue

This happens when calling :Black from a python buffer and then the code does not format.

To Reproduce

Use this `...

late dewBOT
#

:incoming_envelope: :ok_hand: applied mute to @long shuttle until <t:1665340032:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

plain atlas
#

what happened to the hyperlinks? (did they ever exist?)

#

not clickable

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

Also good gosh Black has been active in the past 24 hours

plain atlas
#

really should be

#

it's not too hard to implement, I might be able to do it without breaking the blame, too

bright glacier
#

I would've just created a sphinx plugin, but fair enough lol

plain atlas
#

there is a sphinx plugin in which you can use :anytexthere:`anythinghere` and it'll make a link

#

often used as :issue:`123`

#

and I'm pretty sure said plugin is bundled with sphinx

mint barn
#

Talk to you later

bright glacier
plain atlas
#

there's also a replace syntax built in to sphinx parsing which occurs before giving the files to extensions

regal crest
#

Heya! I want to set up black to format my projects in pycharm
Anyone know how to do this so it'll work for every project when I create it?

flat krakenBOT
#

Describe the style change

When an import line is too long, and it only has a single imported symbol, it's more readable to NOT wrap the line.

Examples in the current Black style

from company.organization.products.my_awesome_learning_system.backend.handlers import (
    register,
)
from company.organization.products.my_awesome_learning_system.common import logging
from company.organization.products.my_awesome_learning_system.utils import (
    authent...
errant barn
toxic stormBOT
flat krakenBOT
#

Description

I used the Black github action workflow in one of my projects and passed arguments via options. Because I had initially omitted '--check', my workflow did not fail, although Black found files that needed formatting. I would like to suggest this one sentence that makes that even clearer. It would have saved me some debugging time, as I am quite new to GitHub action workflows.

Clarifies ...

flat krakenBOT
flat krakenBOT
flat krakenBOT
small knot
#

does black support plugin? I want to use it for airflow dags.

dense jungle
lament crow
flat krakenBOT
flat krakenBOT
#

A long line is split into multiple lines if it exceeds the black_line_length setting.
How to not take the comments into consideration to compute the line length?

Example:

# this one should still be broken into multiple lines
long_function(param_1="this is a long line, longer than 80 characters", param_2="this is a long line, longer than 80 characters")  # comment here

# this one SHOULD NOT be broken because the code is smaller than 80 char
short_function(para...
flat krakenBOT
#

I have this code:

def function():
    from . import something_long_long_long_long  # pylint: disable=import-outside-toplevel

black formats it to:

def function():
    from . import (
        something_long_long_long_long,
    )  # pylint: disable=import-outside-toplevel

This breaks the Pylint pragma, it does not work anymore on the line where black has put it. So, I played around with the pylint and black pragmas to get it working:

def function...
bronze heath
#

hi everyone, I just joined Discord, nice to meet y'all. Started using black formatter in my project. Wondering how to the make the imports absolute, automatically from vscode's intellisense?

I mean, if I have a function defined in this file - project/lib/utilities/file.py#readFile(path: str) , and when I try to import this function into some other .py file, I simply type readFile(...), and when I try to take vscode's help to automatically add the imports, it's just adding from utilities.file import readFile.

Is there a way I can have the automatic import use full paths instead? like from project.lib.utilities.file import readFile ? TIA

(P.s: also not sure if this questions should be asked to black or vscode ? let me know if this doesn't belong here please, I can check with vscode's peeps)

errant barn
bronze heath
dense jungle
half meteor
#

is this an old bug in black? can't seem to reproduce it in latest version

dense jungle
#

it's not a bug. they were matching on quotes in the code and black changed the quote style

#

I mean it's not a bug in black

half meteor
#

ah, got it

plain atlas
#

black#3320

#

i'm a bit surprised that there wasn't a discussion on it ๐Ÿ˜…

#

since i'm not sure my proposed solution is the best

lament crow
#

psf/black#3320

flat krakenBOT
flat krakenBOT
#

Fantastic work overall! Your tests are great and your code was easy to follow. As mentioned earlier, I do have a few stylistic critiques and suggestions to make the logic more robust.

Also two general comments:

  • Should we emit a message telling the user what we inferred the target version to be as part of --verbose?
  • By inferring a default for --target-version, Black will never do per-file auto-detection if project.requires-python exists and is valid. This is certainly better ...
bright glacier
#

Oh man that took ... like an hour to review ๐Ÿ˜…

#

I didn't even notice how much time had passed, that's how focused I was.

bright glacier
#

I'm not entirely sure about psf/black#3323, while it's a good idea in theory, Black doesn't have a grammar for each Python version and things can get confusing

toxic stormBOT
bright glacier
#

I'll have to think about it for a little bit

bright glacier
#

Good way to truly understand what changed since honestly I haven't been following what's happening that closely lately. My GitHub inbox is a mess.

errant barn
flat krakenBOT
#

Describe the bug

Black is overzealous about reformatting docstrings to a single line, and can cause the resulting line to be longer than the line length limit.

To Reproduce

For example, take this code:

def f():
    """89 123456789 123456789 123456789 123456789 123456789 123456789 123456789 12345678
    """

The first line of this docstring is exactly 88 characters. After blackening this code, this results in:

def f():
    """89 123456789 123456...
flat krakenBOT
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
#

Description

Fix #3291 : incorrectly ignoring .gitignore presence when more than one source directory is specified. Commit message of the commit that fixed the bug:

When passing multiple src directories, the root gitignore was only applied to the first processed source. The reason is that, in the first source, exclude is None, but then the value gets overridden by re_compile_maybe_verbose(DEFAULT_EXCLUDES), so in the next iteration where the source is a directory, the conditi...

flat krakenBOT
flat krakenBOT
#

Description

Fix #3315 : Fix incorrectly applied .gitignore rules by considering the .gitignore location and the relative path to the target file. Commit message of the commit that fixed the bug:

When a .gitignore file contains the special rule to ignore every subfolder content (*/*) and the file is located in a subfolder
relative to where the command is executed (root), the rule is incorrectly applied and ignores every file at the same level of the .gitignore file.

The...

plain atlas
#

does black have a policy about pep 257 in addition to pep 8?

dense jungle
plain atlas
#

that's disappointing

#

the preview format violates pep257 but the stable form doesn't

#

and i think it looks much worse in the new form

dense jungle
#

do you mean the thing where we put the closing quotes on their own line? I agree we should change that

flat krakenBOT
#

Description

Issue https://github.com/psf/black/issues/2097 raised the issue that is_type_comment only works for comments starting with # type:, and more spaces/tabs between # and type, or typeand : are valid as per typed-ast/ast, but not black.

This PR (for now!) only tries to make is_type_comment be consistent with typed-ast, not to remove the extra spaces/tabs if they are present.

I'd like some guidance as to:

  • Using regex. Is there a way to perform this c...
flat krakenBOT
#

Describe the bug

When running black using pre-commit against a generated Django migration file, the following error is observed:

โžœ  backend git:(main) โœ— pre-commit run black --all-files             
black....................................................................Failed
- hook id: black
- exit code: 123

error: cannot format backend/src/black_test.py: maximum recursion depth exceeded while calling a Python object

Oh no! ๐Ÿ’ฅ ๐Ÿ’” ๐Ÿ’ฅ
167 files left unchanged, 1 file fa...
bright glacier
#

I vaguely remember a pre-existing issue about this, hmmmmm

left snow
#

@GitHub#0000

#

It's broken ๐Ÿ˜‚

little parrot
#

thats how all webhooks show up

plain atlas
flat krakenBOT
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

Sometimes I find myself needing small tables of data for configuration, for example a table containing units and upper and lower bounds for some pandas.DataFrame.

An example:

metadata = {  # formatted with black
    "Glucose": ["g/L", 0, 20],
    "DOT": ["%", 0, 100],
    "Volume": ["mL", 0, None],
}

I am deeply convinced that for this kind of manual data entries in source code, **fixed width ...

flat krakenBOT
#

https://github.com/asottile/blacken-docs

I don't really know how to do this so I'll try and be succinct -- sorry this is off topic as well and that I deleted the issue template

for me, maintaining blacken-docs no longer sparks joy -- and it's not due to the integration with black (which has been fine since stable) -- but because docs are complicated (and, well, I don't actually use it).

I'd love to figure out a way forward where either this is adopted or integrated in some way...

bright glacier
#

Hmm, while my instinct is to help take on maintainership of the project, I barely can keep up with maintenance of Black so it's probable I can't reasonably pick up another project.

#

I have some thoughts about this, but I'll write them up later once I have some free time

wise lantern
#

Getting the error
<_io.TextIOWrapper name=4 encoding='cp1252'>

flat krakenBOT
flat krakenBOT
#

Describe the bug

When I run Black as a commit hook via pre-commit it ignores # fmt: skip on a long lines (mb somewhere else).
I afraid that it may ignore # fmt: skip pragmas totally, making Black unusable for me as a pre-commit tool.

To Reproduce

have a pre-commit with .pre-commit-config.yaml

# Pre-commit config, see: https://pre-commit.com/
repos:
  - repo: https://github.com/psf/black
    rev: '22.10.0'
    hooks:
      - id: black

install hooks ...

flat krakenBOT
#

Black breaks long lines with multiple sets of parentheses at the first set of parentheses that is before the character limit, as far as I can tell. This is a problem when you have lines like this:

    assert nx.number_of_selfloops(G) == len(arch_elements), f"Not all elements have self-loops:\n  {set(arch_elements) - set(nx.selfloops(G))}"

Because black breaks them like this:

    assert nx.number_of_selfloops(G) == len(
        arch_elements
    ), f"Not a...
flat krakenBOT
#

Description

Closes #2484
Closes #2382

Currently, empty and whitespace-only (with or without newlines) are not modified. In some discussions (issues and pull requests) consesus was to reformat whitespace-only files to empty or single-character files, preserving line endings when possible. With that said, this PR introduces the following behaviors:

  • Empty files are left as is
  • Whitespace-only files (no newline) reformat into empty files
  • Whitespace-only files (1 or more newl...
flat krakenBOT
#

No, tabs for indentation are the devil. Making this configurable would go against Black's philosophy.

_Originally posted by @ambv in https://github.com/psf/black/issues/47#issuecomment-374964663_

I'm brining up again. I found one fork that uses tab's but its getting old. I'm not going to try to reason why tabs are better (and believe me I have good reasons). I'm trying to make working fork right now but hitting hard with tests, I've modified the tests to include tabs instead ...

slow ibex
#
>black -c "(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)"
(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(
    1,
)

>black -c "(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1)"
(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(1,)(
    1,
)(1)
``` weird ๐Ÿ™‚
atomic barn
#

out of curiosity, why is a set used here instead of a tuple? aren't tuples more efficient?

# black/__init__.py
def _format_str_once(src_contents: str, *, mode: Mode) -> str:
# ...
  empty_line = Line(mode=mode)
  after = 0
  split_line_features = {
    feature
    for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF} # <- Here
    if supports_feature(versions, feature)
  }
  for current_line in lines.visit(src_node):
# ...
bright glacier
bright glacier
# flat kraken

I wonder if this is hacktoberfest related. Folks running spellcheckers so they can file easy PRs.

atomic barn
bright glacier
#

that does seem like a fun one to debug, I'd guess an earlier bugfix led to this bug

flat krakenBOT
dense jungle
flat krakenBOT
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

As I've been working on some black issues and overall getting a hang of the repo, I got really frustrated when debugging methods which name an arg or a variable as the built-in type, for example
def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing

You can find many of these with pylint src --disable=all --enable=redefined-builtin

Describe the solution you'd like

There ...

flat krakenBOT
primal sphinx
flat krakenBOT
flat krakenBOT
bright glacier
#

IIRC that PR changed the empty line tracking logic substantially. That might kill my post-docstrings empty lines PR haha

flat krakenBOT
flat krakenBOT
#

pytest-xdist 3.0.2 was released today and broke our CI with a DeprecationWarning. On a quick look I couldn't figure out how to fix it (we don't use the rsyncdir option explicitly), so I pinned pytest-xdist to Traceback (most recent call last):
INTERNALERROR> File "/home/runner/work/black/black/.tox/311/lib/python3.11/site-packages/_pytest/main.py", line 266, in wrap_session
INTERNALERROR> config._do_configure()
INTERNALERROR> File "/home/runner/work/black/black/.tox/311/lib/pyth...

bright glacier
#

Ah don't worry about it, the chance of me getting to it anytime is about zero anyway ๐Ÿ˜…

flat krakenBOT
upbeat lava
#

Black doesn't seem to be able to handle the double .replace() line in

dump.writelines(
  [   
    "Blabla\n",
    raw_dump.stdout.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1).replace(f"Database: {schema}", f"Database: `{PLANT_CODE}_{schema}`", 1),
  ]
)

Do I just need to nudge it in the right direction or is this outside of Black's capabilities? The line is clearly too long.
Personally, I'd probably do something like this.

dump.writelines(
  [   
    "Blabla\n",
    raw_dump.stdout.replace(
      "CREATE TABLE",
      "CREATE TABLE IF NOT EXISTS",
      1).replace(
      f"Database: {schema}",
      f"Database: `{PLANT_CODE}_{schema}`",
      1
    ),
  ]
)
#

Or is this just a case of something Black shouldn't even begin to deal with because I should have done the replacements in previous lines to not have this mess in the first place?

glacial drum
#
dump.writelines(
    [
        "Blabla\n",
        raw_dump.stdout.replace(
            "CREATE TABLE", "CREATE TABLE IF NOT EXISTS", 1
        ).replace(f"Database: {schema}", f"Database: `{PLANT_CODE}_{schema}`", 1),
    ]
)
#

what version of black are you running?

upbeat lava
#

22.10.0

glacial drum
#

and it doesn't give the above output?

upbeat lava
#

While playing around, I just found out that Black isn't actually doing anything at the moment in VS Code.

#

I think something is wrong with the integration

#

I just moved up a function definitions two lines and it didn't move it back. Which it was doing just recently.

glacial drum
upbeat lava
#

Yeah, thought it was a Black problem initially but doesn't seem like it

flat krakenBOT
#

Hello! :heart: :laughing: :rofl: :smile:

First :one: of all, thank you :bow: for an amazing tool. :lollipop: I use it all the time. :watch:

I wrote a tool :wrench: which cleans :soap: :bath: :shower: all(:question:) emojis :hankey: from Black's :black_flag: output:

pip install . installs an executable script named black. Whenever you run it, it will run the next-in-line executable named black in your which -a black, and filter both stdout and stderr through a regular expr...

worthy tulip
#

is there a way to stop black from adding two empty lines after a function or class

slow ibex
#

is it bad?

worthy tulip
#

yes

#

i hate how it looks

slow ibex
#

in some place i have huge hierarchy of empty classes (dont ask me why)

class Base: ...
class A(Base): ...
class B(Base): ...
class C(B): ...
class D(A): ...
# etc...

i need to put #fmt: off around this code, otherwise every line becomes 4 lines (class def line, ... line, two empty lines)
please consider the following suggestion: if class body is empty (pass or ...), dont add empty lines after class and leave class body on same line

worthy tulip
#

but it will auto insert them

flat krakenBOT
#

Describe the bug

In the following code:

import math

# a most excellent class
class MyClass:
    PI = math.pi

Black fails to add an extra newline before the comment. This causes flake8 to give an E302 error.

Black does add a newline if you delete the comment, so I think this is an issue with Black.

To Reproduce
Run this in Bash on a Linux/Unix system:

cat > foo.py <<EOF
import math

# a most excellent class
class MyClass:
    PI = math.pi
EOF

...
flat krakenBOT
dense jungle
#

I wonder if we should change "Facebook" to "Meta" in that list ๐Ÿ™‚

flat krakenBOT
#

Description

This fixes #3350.

The problem is that when Black encounters standalone comments on one line inside brackets, it splits the line using delimiter_split. This will split on the comment, but it will also split the line on the highest priority delimiter, which isn't always necessary.

I've added a comma_split function, which is the same as delimiter_split, but delimiter_priority = COMMA_PRIORITY. Black will now try comment_split before it tries delimiter_split. Th...

flat krakenBOT
flat krakenBOT
#

Say I'd like to format my code like so:

v = (
    foo_dict
    .setdefault("a", {})
    .setdefault("b", {})
    .setdefault("c", {})
    .setdefault("d", {})
    .setdefault("e", {})
)

Black will of course reformat this to put foo_dict.setdefault("a", {}) on the first line.

Luckily, there are [directives to not auto-format some lines](doesnโ€™t reformat lines that end with # fmt: skip):

[black] doesnโ€™t reformat lines that end with # fmt: skip

Yet this doesn't w...

flat krakenBOT
#

Revert deleted documentation on setting up Black using IntelliJ external tool or file watcher utilities

Issue: https://github.com/psf/black/issues/3271

Description

Add documentation section on how to set up black in IntelliJ products using either File Watcher or External Tools utilities

Checklist

  • [x] Add an entry in CHANGES.md if necessary?
  • [x] Add / update tests if necessary?
  • [x] Add new / update outdated documentation?
rough parcel
#

How do I locally compile the repository?

I want to use black with personal modifications (the community doesn't want it, for sure, saw discussions about it)
I forked black, I installed everything needed, and I can now pass all tests with "tox -e py".
how do I compile it? when I run "mypy src --config-file mypy.ini" it throws

error: Library stubs not installed for "typed_ast" (or incompatible with Python 3.7)

The venv is python 3.9.
pip freeze shows:

aiohttp==3.8.3
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
-e git+https://github.com/YuvalZilber/black.git@4bb6e4f64ab3820ab9fae6716cd59479d34b7edf#egg=black
cfgv==3.3.1
charset-normalizer==2.1.1
click==8.1.3
coverage==6.5.0
distlib==0.3.6
exceptiongroup==1.0.0
execnet==1.9.0
filelock==3.8.0
frozenlist==1.3.1
identify==2.5.8
idna==3.4
iniconfig==1.1.1
multidict==6.0.2
mypy-extensions==0.4.3
nodeenv==1.7.0
packaging==21.3
pathspec==0.10.1
platformdirs==2.5.2
pluggy==1.0.0
pre-commit==2.20.0
py==1.11.0
pyparsing==3.0.9
pytest==7.2.0
pytest-cov==4.0.0
pytest-forked==1.4.0
pytest-xdist==2.5.0
PyYAML==6.0
six==1.16.0
toml==0.10.2
tomli==2.0.1
tox==3.27.0
typing_extensions==4.4.0
virtualenv==20.16.6
yarl==1.8.1

ivory quest
#

try looking into CI, how it's compiled there

tribal thistle
#

Hey could someone provide a sample to test black with different target-versions? I'm not quite clear how it's meant to work, and I'd like to test if my configuration is picked up correctly

#

Ah, I've managed to find the list of feature: version, I think I can figure it out from here

flat krakenBOT
flat krakenBOT
half meteor
#

Is there a convenient way to run locally whatever diff-shades runs on the CI?

flat krakenBOT
#

Description

Correctly handle trailing commas that are inside a line's leading non-nested parens.

  • Fixes #1671
  • Fixes #3229

This also improves the formatting on #2052, though it still results in unnecessary line breaks:

# Unformatted:
x = {
    "string": str,
    "integer": int,
}[key](value)

# Before the fix:
x = {"string": str, "integer": int,}[
    key
](value)

# After the fix:
x = {
    "string": str,
    "integer": int,
}[
    key
]...
slow ibex
#

TIL: black is formatting #fmt:off and #fmt:on comments

dense jungle
half meteor
half meteor
bright glacier
bright glacier
#

there ya go

half meteor
bright glacier
#

The workflow used to support workflow_dispatch so you could call it manually (on any revisions) but I got rid of it because no one used it

bright glacier
half meteor
#

workflow_dispatch still runs the CI not locally right?

bright glacier
#

yeah

bright glacier
# half meteor Yes that would be helpful. I'm working on two PRs where I need diff-shades to fi...

The best way of running diff-shades like CI locally would be to...

  1. Download the latest preview-changes analysis for main from the PR (or a recent one if the current PR does not have a passing run yet) -- you can download preview-changes-main-f67791427d.json from https://github.com/psf/black/actions/runs/3365491825
  2. Install diff-shades locally python -m pip install https://github.com/ichard26/diff-shades/archive/main.zip
  3. Install your local copy of Black in the same environment you installed diff-shades
  4. Run diff-shades analyze your-copy.json --work-dir projects-cache/ --repeat-projects-from downloaded-main-analysis.json
  5. Run diff-shades compare downloaded-main-analysis.json your-copy.json --diff (probably want to redirect to a file)
half meteor
#

oh thanks! I didn't realize the trick to download the results from an existing run for comparison

bright glacier
#

Yeah, you could gather your baseline data for main yourself, but downloading it from a pre-existing run is faster :)

#

I understand this is a little confusing if you aren't the one who wrote diff-shades :)

bright glacier
#

Actually, you can replace all of the file extensions with .zip, diff-shades has built-in support for zipped analyses

flat krakenBOT
#

Describe the bug

Black does not break lines containing class member access even though character line limit is exceeded.

To Reproduce

Given this code using dataclasses with long member names:

from dataclasses import dataclass


@dataclass
class SomeNestedDataclass:
    very_long_nested_dataclass_variable_name: str


@dataclass
class SomeDataclass:
    long_dataclass_variable_name: SomeNestedDataclass


def some_func(some_datclass_param):
    pass
...
flat krakenBOT
#

Describe the bug

To Reproduce
Run black on this code, and observe a change that should not have happened.

def recv(
    self,
) -> (
    # fmt: off
        gym_old_venv_step_type     # old API step
        | gym_new_venv_step_type   # new API step
        | tuple[np.ndarray, dict]  # new API reset
        | np.ndarray               # old API reset
):  # fmt: on # noqa:E125
    ...

Reformatting happens on the line before # fmt: on, with comment moved...

neon loom
#

Is there a way to tune my black notifications to not tell me about draft PRs that I missed?

half meteor
neon loom
#

Yup. I get em ๐Ÿ™‚

half meteor
#

I didn't realize that, I'll keep that in mind.

vague bronze
#

why does black format ' to "?

#

is it based on the python style guide

slow ibex
#

you can disable it by using --skip-string-normalization/-S flag

half totem
#

Hi everybody, I have a peculiar error when trying to use black.

$ black
Traceback (most recent call last):
  File "/home/ale/miniconda3/envs/sfhfinder/bin/black", line 7, in <module>
    from black import patched_main
  File "src/black/__init__.py", line 41, in <module>
  File "src/black/nodes.py", line 37, in <module>
  File "src/blib2to3/pygram.py", line 186, in initialize
  File "src/blib2to3/pygram.py", line 32, in __init__
AttributeError: '_python_symbols' object has no attribute 'tname_star'

I do not know how to solve it, but I do not want to open an issue immediately.

I'm using Python 3.10.6 and Black 22.3.0.

dense jungle
half totem
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

I'm used to run black --check --diff --color to see format suggestions by Black and apply them myself. I do this because I intend to improve my coding skills by reading and writing better code, and also because sometimes renaming a variable, using a better indentation or placing a comma properly is a task that a human can do better than Black (sometimes). I've recently faced some problems when the output of the diff is t...

flat krakenBOT
#

This is most apparent when black is run via pre-commit which does
subprocess.Popen(stdout=PIPE).

One option around this would be to instruct users to set PYTHONUTF8=1,
but that is not a very good approach, as basically everything supports
UTF-8 these days.

This fix was inspired by pycln and https://github.com/hadialqattan/pycln/issues/54

Fixes #3156

Checklist - did you ...

  • [x] Add an entry in CHANGES.md if necessary?
flat krakenBOT
#

Thanks for your contribution!

Monkeypatching sys.stdout feels quite risky though. A few questions:

  • What will happen on Windows terminals that use an encoding incompatible with UTF-8? I'm worried we'll get mojibake in that case.
  • Could this be fixed in click instead? We use click.echo to output all emoji, and click is supposed to take care of output encoding for us.
  • The pycln issue reported getting UnicodeEncodeError, while the OP of the Black issue saw literal \u1234 ...
lament crow
#

just for transparency, we briefly talked about it before

#

I definitely did some testing back then which worked but I think I ran into some wall with a case where it doesn't quite work and just dropped it. No idea what the case was so there's that lol

flat krakenBOT
#

Is this related to a problem? Please describe.

This is a suggestion to improve some ambiguity in the Pragmatism section of the documentation.
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#ast-before-and-after-formatting

Current text (first paragraph of section 'AST before and after formatting')

When run with --safe, Black checks that the code before and after is semantically equivalent. This check is done by comparing the AST of the source with t...

flat krakenBOT
bright glacier
#

I was genuinely confused hearing the Discord notification sound for this. It didn't register this was caused by my review ๐Ÿ˜…

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 `...
elder tusk
#

how's black's mypyc stuff doing these days? i know for a bit there was some stuff blocking you from using latest mypy... is that all resolved?

dense jungle
bright glacier
#

There isn't any, other than me testing it out and then bumping mypy in pyproject.toml

dense jungle
bright glacier
#

Nope, I typically just bump mypy in my personal black-mypyc-wheels repository and fire a test build and verify it passes

#

I should really document and make myself not the SPOF for all things mypyc related....

dense jungle
bright glacier
#

I'll add that to my to-do list for Black

#

actually it's already on there since August 3 ๐Ÿฅด

slow ibex
#

does black supports plugins?
for example, plugin can preprocess source code so black can understand it, then black formats it, and then plugin preprocesses code back

slow ibex
#

sad :(

#

i think i can write wrapper around black

dense jungle
#

yes, that's possible

#

we don't formally have an API but you can also import black and call black.format_str

slow ibex
#

it's quite convenient, thanks

half meteor
dense jungle
half meteor
#

then Black merged it later

flat krakenBOT
flat krakenBOT
bright glacier
#

Shoot, of course upon merge I realized this is targetting the stable branch.

dense jungle
#

just saw that too in the email

bright glacier
#

I'll fix that, but man what a terrible start to the morning.

dense jungle
#

might have to force push it out?

bright glacier
#

Yeah, I'll do git switch stable && git reset HEAD~1 && git push --force

#

So this is the one actual downside of stable being a branch. We fix RTD but we get these PRs ๐Ÿ˜…

dense jungle
#

I wonder if GH has a config to disallow PRs by branch

bright glacier
#

I was wondering the same thing

#

You can lock a branch, but that makes it read-only to everyone (even GHA I'd imagine), hmm.

dense jungle
#

yeah that's what it looks like

#

oh wait do we have automation now to update the branch? pretty sure I can make it so only GHA can push to it

bright glacier
#

Yup, but how? Reading the docs doesn't show any option to do that...

dense jungle
#

not sure what to put in this box though ๐Ÿ™‚

bright glacier
#

Neither do I

#

I guess the best option to add a simple step to the lint workflow that fails if the target branch is wrong

dense jungle
#

I'll make an issue

bright glacier
#

TIL you can do git cherry-pick stable, very nice.

flat krakenBOT
dense jungle
bright glacier
#

Anyway I feel like an idiot.

dense jungle
#

don't worry about it! it's very easy to miss

flat krakenBOT
bright glacier
#

I think this is my first time pushing to main directly haha

dense jungle
#

if you hadn't done it I'd have merged that PR and made the same mistake

bright glacier
#

OK moved the commit from stable to main.

bright glacier
#

Thanks for opening the issue!

bright glacier
bright glacier
#

FWIW, I'm going to try to at least catch up on the recent PR activity today, so if there's any PRs ready to be merged, I'd appreciate waiting.

slow ibex
dense jungle
slow ibex
#

Yeah, nice and convenient idea

austere lava
#

has anyone seen setuptools-scm produce a version file with completely zeroed out content? or alternatively cibuildwheel producing a wheel where a file is zeroed out?

bright glacier
#

Nope, how odd.

flat krakenBOT
flat krakenBOT
bright glacier
#

I feel bad reviewing so late.

#

I got through a little bit of the backlog, but I still have a ton of stuff to catch up on. Looks like I'll have to do this piece by piece day by day since I don't much free time these days.

#

The problem is that proper PR reviews take tens of minutes if not hours and I'm not willing to sacrifice that since quality is important.

bright glacier
#

Oh wow, upgrading mypy to 0.990 doesn't net any new type errors.

flat krakenBOT
#

Thanks for writing this up and putting it under the preview style.

I'm not yet convinced we should do this, since it could be disruptive. diff-shades currently gives us results only for pyanalyze (which happens to be my code), because it runs black with preview = True. As you see, I currently use a different docstring style :)

I'd be curious to see the result on more open-source code. Could you push a change to enable the new style without preview mode, so that we can see the diff-sha...

oblique lava
#

How would i format on save using black? (I use nvim btw)

slow ibex
#

you need plugin for nvim

ivory quest
#

I think you can use the vim plugin, that black offers, with neovim as well

oblique lava
#

Is it official?

#

Nvm found it.

flat krakenBOT
bright glacier
#

diff-shades preview-changes is getting concerningly slow. I should probably start looking into implementing sharding.

#

Or alternatively split the baseline and target revisions across multiple jobs

neon loom
#

Oooo new mypyc

#

Very nice

late dewBOT
#

@chrome plover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

flat krakenBOT
#
black, 22.10.0 (compiled: yes)
Python (CPython) 3.10.2

After applying Black:

def f2(some_name1, some_name2):
    if (some_name1.is_constant or some_name1.is_affine) and (
        some_name2.is_constant or some_name2.is_affine
    ):
        pass


def f3(some_name1, some_name2):
    if (
        (some_name1.is_constant or some_name1.is_affine)
        and (some_name2.is_constant or some_name2.is_affine)
        and (some_name3.is_constant or some_name3.i...
flat krakenBOT
#

I'm alright with making the default Black version tied to the action version being used. For context version was introduced because the action didn't exist for a long time so tying black version to action version wouldn't work for version 19.10b0 for example. In hidesight, having the default being the action version keeping the version configuration option around as an escape hatch is the better solution. This will involve some complexity since commit SHAs aren't supported by the versio...

flat krakenBOT
#

Description

Minor tweak to the language in the description of the current style.

In a nutshell, I think the original author meant to say "real-world" rather than "realtime."

Checklist - did you ...

  • [x] Add an entry in CHANGES.md if necessary? -> not necessary
  • [x] Add / update tests if necessary? -> not necessary
  • [x] Add new / update outdated documentation?

My understanding is that this PR should get the magical label to silence the CHANGELOG entry check.

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

When trying to format a project from the outside, the verbose output shows says that there are symbolic links that points outside of the project, but displays the wrong project path. This behavior seem to be triggered when the command is executed from outside a project on a folder.

To Reproduce

Consider the following tree:

.
โ””โ”€โ”€ home/
    โ””โ”€โ”€ project/
        โ”œโ”€โ”€ .git
        โ””โ”€โ”€ dir/
            โ””โ”€โ”€ main.py

When trying to format a fol...

flat krakenBOT
#

Description

Closes #3384

When trying to format a project from the outside, the verbose output shows says that there are symbolic links that points outside of the project, but displays the wrong project path. This behavior seem to be triggered when the command is executed from outside a project on a folder, causing an inconsistency between the path to the detected project root and the relative path to the target contents. The fix is to normalize the target path using the project roo...

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

Sometimes when dealing with multiple environment settings, IDEs, and pyproject.toml files etc. etc. is beneficial for a project team to have a confirmation about the actual applied black-settings ("line length") in the CI CD pipeline.

black -v will show a line like this: Using configuration from project root..
However, it doesn't tell us what the settings are, and it is not desirable to have all the other output of...

half meteor
dense jungle
#

we should make sure everything we put into stable is performant. IIRC part of the reason we didn't move experimental string processing to stable before is that it has quadratic performance in some edge cases, I'll have to check if that's still an issue

#

relatedly, 2023 is approaching, so we should make decisions on what parts of the preview style to move into stable

#

I think in early December I'll make an issue to discuss all the preview changes and decide whether any should be reversed or left in preview for now

half meteor
#

This is all great, thanks!

flat pecan
#

Hi. I'm the person behind this pull request https://github.com/psf/black/pull/3377. So I think that the behavior I changed is a bug fix in that the previous behavior caused formatting bugs by both yielding early and not yielding still-omittable sibling-level trailers after exiting prematurely due to finding magic commas.

The regression in trailing_comma_optional_parens2 is due to a slight change in the parse tree: picking the first tuple instead of the second one as the place to insert the magic commas. This is probably because the length escape for generate_trailers_to_omit also will yield omittable trailers, but is somewhat inconsistent the existing behavior of the function. The change I applied minimizes the number of regressions, but it also defeats the point of using the generator. At this point, I'm unsure of where to go next or if this will require more of a rewrite.

GitHub

GitHub is where people build software. More than 94 million people use GitHub to discover, fork, and contribute to over 330 million projects.

flat pecan
#

Looking at the differences in the assert-no-changes CI job, some previously bad lines such the one below are fixed, but there are several breakages where the RHS is kept together tighter than the rest when as per https://github.com/psf/black/pull/3368, the RHS should be split first.

--- a/django:tests/queries/tests.py
+++ b/django:tests/queries/tests.py
@@ -3320,13 +3320,13 @@
         ) | JobResponsibilities.objects.exclude(
             job__responsibilities__description="foo",
         )
         self.assertCountEqual(
             Job.objects.annotate(
-                responsibility=subquery.filter(job=OuterRef("name"),).values(
-                    "id"
-                )[:1]
+                responsibility=subquery.filter(
+                    job=OuterRef("name"),
+                ).values("id")[:1]

The long-line problem where long lines will all of the trailers at once instead of incrementally is also showing.

flat krakenBOT
exotic stratus
#

Been using black for quite some time, great job on it. One question I would have for easier navigation, perhaps, are there any thoughts of including the following when passing the --diff flag:
1. have the + and - signs be colored for better visibility
2. enumerate the affected lines with their respective line numbers
I think these would be quite a nice qol changes on a daily. Thank you

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Is your feature request related to a problem? Please describe.

If a user wants to require a certain aspect in pyproject.toml, he can do it. If he doesn't do it, then it means he doesn't care. It should be up to the global config of the one running the tool. If a user wants to enforce the black-default value, he can define a field, but leave it as None and black should set the default value for that field.

Describe the solution you'd like

config = dict(globalC...
flat krakenBOT
flat krakenBOT
flat krakenBOT
open goblet
#

is this the expected behavior?

    encoding = tokenizer(text, return_tensors=FRAMEWORK, truncation=True,).to(
        device
    )  #

vs

    encoding = tokenizer(
        text,
        return_tensors=FRAMEWORK,
        truncation=True,
    ).to(device)

the # negates the trailing coma

pip freeze | grep black
black==22.10.0
flat pecan
#

I started on a fix, but it causes some regressions and I'm not sure how to move on

bright glacier
bright glacier
#

You're welcome to open an issue to make --color the default FWIW.

neon loom
#

Im down for color default. It might make some logs messy if we donโ€™t detect non terminals correctly but we use a mature library for color right? (Canโ€™t remember what we use)

#

And, should that go into preview? LoL

#

As in, itโ€™s not changed till 23.1.0

dense jungle
#

seems like the --color flag only affects diffs for what it's worth. I feel like a lot of --diff users probably use the output programmatically somehow, in which case color may be bad

#

And we don't need to wait for 23.1.0 to change this, since it doesn't affect formatting

flat krakenBOT
#

Is your feature request related to a problem? Please describe.

I'm trying to integrate black into a bazel project, run as a bazel test, to check python formatting at precommit. For sandboxing reasons, bazel tests don't run on the source files directly, but on a special output directory with symlinks to the source files. However, black skips symlinks, so it skips all the files and reports success, without actually having checked any of the files.

Describe the solution you'd like
...

solemn terrace
#

what is black formatter?

bright glacier
slow ibex
#

is there #fmt:off, but only for one line?

# fmt: off
x=[1,2,3,4,5]
# fmt: on

# VS

x=[1,2,3,4,5] # fmt: off-one-line
bright glacier
#

# fmt: skip

slow ibex
#

nice ๐Ÿ‘

#

i knew skip exists, but didnt know what it is doing. Now i know

solemn terrace
#

Anyone know what a black formatter is ?

solemn terrace
flat krakenBOT
#

Hey there!

I just noticed that under the following configuration:

  • Ubuntu 20.04 with the following kernel:
    Linux ubuntu 5.15.0-53-generic #59~20.04.1-Ubuntu SMP Thu Oct 20 15:10:22 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
  • Using python 3.10 installed via apt from the ppa:deadsnakes/ppa repository:
    • Python 3.10.8 (main, Oct 12 2022, 19:14:26) [GCC 9.4.0] on linux
    • pip 22.3.1 from ~/black_test/lib/python3.10/site-packages/pip (python 3.10)

Installing black on ver...

crimson bough
#

84105992682cfadf3cfbd9ccdaf9246b72e05b2f59e4a751d5398ad6e983ee6f

flat krakenBOT
#

I would love to have Leo use Black as Leo's one-and-only code formatter. That's not possible at present.

The problem

Leo uses sentinels, comments starting with #@ (no space after the pound sign), to denote outline structure. Sentinels appear in the external files that Leo produces.

This convention goes back more than two decades. Recent versions of Leo can read external files with black-formatted sentinels, but writing black-formatted sentin...

flat krakenBOT
dense jungle
# flat kraken

hm when I click that link it takes me to the home page for this server

#

I think it's supposed to be directly for this channel though?

little parrot
#

i think they might just be banned

dense jungle
#

weird, that user has been a very helpful contributor to typeshed

little parrot
#

although i cant find anything from them here

flat krakenBOT
#

Describe the style change

When validating a project with both pyright and mypy, it's possible to independently validate both checkers.
However, both expect their ignore comment to be at the start of the line.

Examples in the current Black style

line-lenght=130

class Task(Future[_T_co], Generic[_T_co]):  # type: ignore[type-var]  # pyright: ignore[reportGeneralTypeIssues]
 # [...]
 pass

Desired style

class Task(  # type: i...
half meteor
hushed drift
flat krakenBOT
#

Description

I wanted to start taking good care of quality of code in my project. In order to achieve this, obviously I had to implement black. When black corrected all my formatting mistakes and then I run it again (just in case) I saw following message (TRIGGER WARNING):

All done! โœจ ๐Ÿฐ โœจ

And I was schocked. I did not even realise how hungry I was, and the cake looked to delicious. I should add that I'm trying to loose weight. This delightful piece of confectionery art wok...

flat krakenBOT
flat krakenBOT
#

So I love named (keyword) arguments, I use them even when they're not required, I think it improves code readability.

def randint(min, max):
    return random.randint(min, max)

randint(
    min = 0,
    max = 2**256 - 1
)

The issue is black removes the whitespace around =, which hinders readability.

In the ideal world, black would offer several options:

  • remove whitespace for named arguments (current)
  • num spaces for named arguments (specify a numbe...
mint barn
#

hello

silent apex
#

"A Foolish Consistency is the Hobgoblin of Little Minds" and all that

#

black rationalizes all of its decisions, and thus complies with pep 8 in that regard

#

but i guess others view that differently ยฏ_(ใƒ„)_/ยฏ

elder tusk
#

(if it were up to me iโ€™d just not mention pep 8. itโ€™ll shut people up. pep 8 was never meant to be a style guide for all of python. blackโ€™s style isnโ€™t going to change regardless)

plain atlas
#

WHAT IS BLACK DOING AGAINST PEP 8?

#

ah, four of those issues linked are about the line length

exotic stratus
#

Uh, first time I see this, but apparently black is trying to reformat code in a way that violates PEP-8?

#

Line in question, after reformatted by black:

compart1, compart2 = rucksack[: len(rucksack) // 2], rucksack[len(rucksack) // 2 :]
little parrot
#

its valid in pep 8

#

but also read up ^ ๐Ÿ˜‰

exotic stratus
#

There's a whitespace before :

exotic stratus
#

A nice, thanks!

exotic stratus
#

Alright, I changed the reformat tool used in pycharm to black, but now it suddenly ignores the configs I set for it in pyproject.toml. Can I have the integration with the IDE read these configs somehow?

#

Seems like a few are present in the formatting options menu of blackconnect, they will be sufficient for now

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 `...
jolly kettle
#
would reformat cogs/autobuy.py
would reformat cogs/commands.py
would reformat cogs/hl.py
would reformat cogs/blackjack.py
would reformat cogs/pm.py
would reformat cogs/search.py
cogs/stream.py already well formatted, good job.
would reformat cogs/trivia.py
would reformat cogs/minigames.py
resources/icons.py already well formatted, good job.
would reformat main.py
resources/interface.py already well formatted, good job.

Oh no! ๐Ÿ’ฅ ๐Ÿ’” ๐Ÿ’ฅ
9 files would be reformatted, 3 files would be left unchanged.
Error: Process completed with exit code 1.```

How can i make the black github action reformat instead of showing an error?
ivory quest
#

overwrite options input

late dewBOT
#

action.yml line 5

options:```
weary vigil
#

I installed black formatter, and I can use it inside Visual Code by using the standard keybind: ALT + SHIFT + F

#

however within the terminal I wish to use a command to execute black. I am using pipenv and I cant get it to work. Let me show you

#

Nvm i solved it by doing:

PS C:\Users\...\pdf_creator> pipenv run black "../pdf_creator"
All done! โœจ ๐Ÿฐ โœจ
9 files left unchanged.
ivory quest
flat krakenBOT
exotic stratus
#

Hmm just curious, at type hints, what is the logic behind removing spaces at dict[int:str] but creating them at dict[int : list[str]]?

little parrot
#

thats not a valid type hint fwiw

#

but its probably cause list[str] is considered a complex expression iirc?

exotic stratus
#

Which of the two is not a valid type hint?

little parrot
#

youre looking for dict[int, str] and dict[int, list[str]]

#

all of them

exotic stratus
#

It seems like you are correct, , is used and not :. Thank you

soft compass
#

I have a custom dialect of Python and I'd like to add black support for some of the specific constructs. Is there an "approved" way of doing this or will I end up needing to fork and hack?

slow ibex
#

you can write wrapper around black

  1. change your code to be valid python
  2. run black on it
  3. change code back
soft compass
winged whale
#

(VS Code)too much linting errors made by flake8, black formatter, how should I change the parameter?

#

If it thinks it's too long, I expect it should help me to split it into 2 lines, isn't it?

dense jungle
winged whale
#

Hello guys!
I start using flake8+black formatter today.

The code works, but the color of the code start going wrong in line 110

#

It's random color now.

#

Is that possible a bug from black formatter? Thank you!

flat krakenBOT
#

Describe the style change

In most cases, when the indentation level decreases, whether it is only one level or many, the previous logical block is ended.
This is true for all cases except when the line immediately after is either an else or an elif or an except.

The proposal is to enforce that a newline (or two for module level) always exists before that indentation level decrease.
This newline works as a visual clue to help the code reader understand which code blocks are l...

flat krakenBOT
#

The first 2023 release is coming up, which means we'll have to decide which parts of the current preview style should go into the 2023 stable style, per our stability policy.

Here's how I propose we go about it:

  • In this issue, I'll list all style changes in the current preview style
  • We'll default to promoting every part of the preview style to the stable style.
  • Anyone can comment here if they have concerns about a particular part of the new stable style. However, if the discussion...
dense jungle
#

fun fact I discovered I can edit release notes for old releases

bright glacier
#

yeah I think I fixed a typo doing that a while back

#

also it's dec. 8 already ๐Ÿ‘€

dense jungle
#

yes I realized today I promised weeks ago to create the issue above ^

bright glacier
#

I'll try to take a look this weekend

elder tusk
#

some of the changes in teststubtest.py are a downgrade (i think i filed a similar-ish issue before though)

flat krakenBOT
#
% cat eatcomment.py 
if False:
    with xxxxxxxxxx(
        "mypy",  # mypy-c doesn't support __package__
        "py.typed",  # a marker file for type information, we assume typeshed to live in the same dir
    ) as xxxxx:
        pass
% black --diff --preview eatcomment.py
--- eatcomment.py	2022-12-09 02:39:37.001919 +0000
+++ eatcomment.py	2022-12-09 02:40:57.322777 +0000
@@ -1,6 +1,3 @@
 if False:
-    with xxxxxxxxxx(
-        "mypy",  # mypy-c doesn't support __package...
dense jungle
elder tusk
dense jungle
elder tusk
#

mypy uses line length 100, i think it's under the length limit

dense jungle
#

no it's 140

elder tusk
#

oh sorry yes obviously i got confused

flat krakenBOT
dense jungle
#

thanks, added to the list of blockers in #3407. I don't think we should add anything to stable style that makes us go over the line length limit

#

and also agree the new formatting is ugly

elder tusk
#

"For 4. We should fix ..." <--- i think this is "for 5"

dense jungle
#

right, thanks

flat krakenBOT
dense jungle
bright glacier
#

I believe only the x86-64 wheels were tagged correctly?

#

I'd have to check the logs, I can in 10 minutes

dense jungle
#

I think we uploaded wheels labeled as x86_64 that were actually arm64

flat krakenBOT
flat krakenBOT
flat krakenBOT
bright glacier
toxic stormBOT
bright glacier
#

Sorry for taking so long to get back to you, totally forgot.

dense jungle
#

oh right, the amd64 job uploaded its wheels but labeled them as x86_64

bright glacier
#

and it was able to do that because it was the first to finish

#

I feel like this is something delocate (auditwheel for macOS) should check for, but I don't even know who maintains that.

dense jungle
#

changed the PR to run only x86_64 instead

bright glacier
#

seems like an issue already exists? matthew-brett/delocate#132

flat krakenBOT
dense jungle
#

thanks for the review!

bright glacier
#

it's the least I can do, but you're welcome

dense jungle
#

ugh tests failed on pypy, I'm going to ignore that because this PR definitely isn't breaking pypy

dense jungle
#

guess we'll have no macos wheels today

#

linux wheels are here though, and the windows wheels are on their way

#

windows is done too