#black-formatter
1 messages · Page 4 of 1
Some tools, including LSPs and useful auto-documentors like pdoc (note: not the malicious and parasitic "pdoc3") allow markdown formatting of docstrings.
That requires the use of trailing whitespace in order to indicate soft line breaks.
However black ([in AST non-respecting fashion](https://black.readthedocs.io/en/stable/the_black_code_style...
Hi, i hope i can get some help here. I'm a bit clueless right now. Our Black setup changed with the new release but because we don't want to deal with it now, we try to pin the version to the one we used all the time: v22.3.0 in this PR:
https://github.com/cryptoadvance/specter-desktop/pull/2121/files
But now the formatting seem to differ a lot with my local black installation and i can't explain that. Also the debugging doesn't seem to be helpful.
ANy hints what i can do? We're happy black user since more than a year.
the version of the action doesn't determine the version of the formatting it uses. see https://black.readthedocs.io/en/stable/integrations/github_actions.html for how to set the version with the action
and yes this is highly confusing and we will change it
Ok, but how can it differ if i haven't specified a specific version, neither in my pre-commit-config not in the github-action config?
$ cat .pre-commit-config.yaml
repos:
- repo: https://github.com/ambv/black
rev: 22.3.0
hooks:
- id: black
language_version: python3.10
$ black --version
black, 22.3.0 (compiled: yes)
the action will use the latest version (23.1.0) by default
and your local config is using 22.3.0
Ahh, ok, got it. that's indeed ... counterintuitive.
Thanks!
yeah I think the original motivation was so that you could use the action to format with Black versions before the one that we released the action with
Anything concrete or is it up for grabs?
https://github.com/psf/black/issues/3382 don't think there's anything blocking this
from @bright glacier's comment seems like this might not be trivial, but I definitely think this is something we should fix soon
I'll look into it today
thanks!
Got me interested
from typing import Literal
ComBloombergDefault = Literal[
"DEFAULT",
]
❯ black magic.py --check
would reformat magic.py
Oh no! 💥 💔 💥
1 file would be reformatted.
It turns it into:
from typing import Literal
ComBloombergDefault = Literal["DEFAULT",]
Description
Resolves #3382
Needs an update to the documentation and an entry to CHANGES.md. I would like to first check with you if this change is acceptable though.
There are 2 things going on here:
- addition of
.git_archival.txtset withexport-substgit attribute so that black can be installed from a git archive, see: https://github.com/pypa/setuptools_scm#git-archives - update to GH action changing it to use GH action version when the version argument is not specifi...
Any devs and/or cooperlees here ? https://github.com/psf/black/pull/3531#issuecomment-1414144301 got me thinking if i understand the comment correctly (context; im trying to help with github actions integration, my pull request async communications via pr comments is a bit "meh" 🙂 )
@neon loom comes from time to time 🙂
Please always tag me as I don't read the channel a lot
What's confusing? (Thanks for taking the feedback tho)
Regardless of however this turns out, I think it's worth adding a guide to the docs about handling Black upgrades, mentioning pinning and --required-version, etc. etc.
I do wish --required-version worked nicely with pre-commit but of course it doesn't.
https://github.com/psf/black/issues/2493 yeah this makes --required-version rather unusable. It might be worth patching Black to only warn if version information is clearly unavailable because we're running under pre-commit).
Heh, my Black 23.1.0 blog post ranks pretty highly on Google!
I was curious to why I was getting so much traffic from Google since usually Google isn't a major source of traffic for these posts.
ah of course, my mypyc stuff is still the most popular
@neon loom so if i got it correctly, the "optimal" way now would be to write the json from black itself and then action just utilizes the json to report it to $GITHUB_OUTPUT ?
thats at least how i understood your comment on the pr .. eg, if black would create a json report directly, that sort of functionality would also support possible other task runners besides github actions and then the action/main.yaml would just use the generated json .. If that is the case, im wondering a bit about maybe there should be a possibility to set the location where the json would go via command line arg ..
(and i btw, truely like this approach better)
@neon loom that said, if the user provides "version" for black, and the version is old enough to not support generating the json, that would cause some issues and worrying part regarding that is that action.yaml still would have reference to outputs but there would be none in case of older black ..
I'd say it's the only good source on applying mypyc to production project with some real-world problems
Yup
Yeah, I feel you just error there and say only supported >= 23.2.0 if it makes it to that version.
mypy itself was a pretty good win to …
but was the whole process covered like it was in the case of black?
I remember reading something. The detail was no where like Richard’s tho.
Describe the bug
Trying to install black in a Docker container (alpine base image) causes an error.
To Reproduce
Create Dockerfile:
FROM alpine:latest
WORKDIR /build
RUN apk update && apk add --no-cache python3 py3-pip
RUN python3 -m pip install black
Try to build it:
docker build .
The resulting error is:
#7 1.868 Installing collected packages: mypy-extensions, tomli, platformdirs, pathspec, packaging, click, black
#7 1.931 ...
Describe the style change
Examples in the current Black future style
items = [
(
{"key1": "val1", "key2": "val2", "key3": "val3"}
if some_var == "longstring"
else {"key": "val"}
)
]
Desired style
items = [
{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
if some_var == 'longstring'
else {'key': 'val'}
]
Additional context
This is a change from https://github....
I'm not sure why mypy doesn't complain.
This was found while I was playing with Pytype on blib2to3.
Let's finally do this :)
Once this is merged I'll update https://github.com/psf/black/labels/T%3A design.
I got fed up with seeing T: design. Sometimes stepping from a project helps with perspective :)
ea5293b Document the future style changes introduced in... - yilei
ff53fc1 Actually add trailing commas to collection lite... - mainj12
e506c46 Rename design label to style because it's clear... - ichard26
I also updated https://ichard26.github.io/ghstats/ because why not
I Hi everyone, I will like to contribute to open source project but need a mentor so as to guide me. I don't know where to start. There is so much information and most of the newbie friendly open source I find are from two years ago.
If someone have already done contributions to open source I will highly appreciate the guidance
Thanks
what is the license on that (and the source)? I would like to copy this for other projects 😄
I might just make it configurable. I know @lament crow also wanted to use it for their own projects. I want to use it for mypyc anyway so it'd be good to remove all of the hardcoding for Black.
Currently all of the front-end and helper scripts assume Black.
or at least I'll make it a lot easier to bootstrap your own copy.
my suggestion would be to find the project you enjoy and look into open issues, join discord or other form of forum the project has (if they do) and start contributing. Contributions are both issue triage (testing older issues if they are still valid, pointing invalid issues as closing candidates to maintainers etc) and actually working on code and PRs. There is not much more philosophy to open source. Have fun at it!
Would be nice. If you were to add license, I might put some work into making it easier to configure and PR it
(as if I didn't have too much work already lol)
I'll try to take a look later today. It's actually split between two repos right now which probably isn't particularly friendly.
You tell me, I'm split between black and mypyc :p
yeah, I noticed. didn't understand the why, just blindly accepted the choice
poetry (3 projects that come into it), blinker, pendulum and few other projects I want to get into
meh, I'll just get started right now. I was going to try and fix one more mypyc bug but this seems to be harder than I previously thought 😅
nice 😄
gosh the python code involved here sucks
def oldest(self) -> Issue:
lowest = min(i for i in self._issues.keys())
return self._issues[lowest]
def newest(self) -> Issue:
newest = max(i for i in self._issues.keys())
return self._issues[newest]
wtf
@ivory quest thanks!
Is your feature request related to a problem? Please describe.
Previously black allowed to have a newline after a code opening black. This can indeed improve readability.
Compare for instance this

with

There are two reasons, why a single newline at the ...
Well... There's a lot of philosophy + political background to the open source movement at large, but that's off topic. I mainly wanna flag that "not much philosophy" isn't correct. 😅
I meant more in terms of "how to start contributing", but I guess some phrases aren't too good when translated to English. Of course there is a lot of philosophy and politics in open source, but for someone just joining the scene, it doesn't really matter most of the time
Describe the bug
This issue is more a heads-up than a bug report.
Follow up of conversation at https://github.com/psf/black/pull/3385. Seems like the test suite does not emulate real-world CLI usage. The paths get mixed up somewhere. This may be hiding some bugs: while writing #3385 I wrote a test to detect a confirmed bug (#3384 ) but the test was not failing, so I had to write a test with some patches to emulate the target behavior.
More details
When trying to repr...
Black https://github.com/psf/black/commit/e506c4
Options
--line-length=88
--safe
Input
some_func_result = some_func(
"Some arg with a comm...
Describe the bug
Add unexpected space before colons in slice when compute start parameter, but omitting other parameters : see https://peps.python.org/pep-0008/#pet-peeves and specially this sentence:
However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted...
Describe the bug
When a comment is placed above a one-liner expression that uses a conditional statement, and --preview mode is on, black changes the comment and one-liner into a parenthesized block, or moves the comment to the end of the expression. The former situation with parentheses happens when the expression is preceded by at least one newline. The latter happens if there is no newline above the comment/expression. Neither of those formatting changes is expected.
**To Repro...
O.o
where is it?
almost makes me think that there's Story involved with code like that .. It could be a bad story but story never the less 😄
def apply(self, func: Callable) -> Sequence[Issue]:
return list(map(self._issues.get, func(self._issues)))
def oldest(self) -> Issue:
return self.apply(min)[0]
def newest(self) -> Issue:
return self.apply(max)[0]
Thank you very much for improving this still, LGTM!
It's been refactored, but here's the file on an older commit. It makes up the GitHub Issues library I wrote a few years ago for issue data visualization. https://github.com/ichard26/ghstats/blob/7a026bf669f4263bb54a3993b3046f28181e7403/scripts/lib.py
👍
Describe the style change
Presently black inserts a space between the "#" and "|" in [Quarto][] metadata comments like #| label: cell1.
Examples in the current Black style
Space is inserted between the hash and the pipe:
# | label: cell-no1
# | echo: false
Desired style
No space between the hash and the pipe, which breaks document metadata parsing:
#| label: cell-no1
#| echo: false
Additional context
Quarto is the new(...
Description
I found this ladybug where if you send one character to blackd it will 500 😳. I created this defect in #3257
Checklist - did you ...
- [🚀] Add an entry in
CHANGES.mdif necessary? - [🚀 ] Add / update tests if necessary?
- [ 🚀] Add new / update outdated documentation?
Nice catch! Changes look good after removing that del
Oh one more thing, could you please add a simple test case for this?
Is your feature request related to a problem? Please describe.
I have a script that reformats all of the code in my project. First it runs isort, then it runs black. Isort lets me specify the paths I want to ignore as globs, which means I can keep the paths looking like filesystem paths, not complicated regular expressions.
black currently only lets me exclude paths with regular expressions, which means I have to maintain two copies of the paths I want to ignore. While regular exp...
Is your feature request related to a problem? Please describe.
Currently the only mechanism for excluding files from black is with a regular expression. Non-trivial regular expressions are notoriously difficult to get right, and so it's not always clear which files black will actually be targeting.
Describe the solution you'd like
Isort has a --show-files flag, that just prints which files isort will operate on. Ideally black would have a similar flag.
**Describe alterna...
Description
Extended COMMENT_EXCEPTIONS to leave alone Quarto metadata comments (#|), cf #3557.
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
@ambv
black has decided to go rogue and started failing the black checks on github workflow see https://github.com/buildtesters/buildtest/actions/runs/4138692064/jobs/7155399872 it was working all of sudden now its failing but there is nothing to black from the code-base. I have the workflow file https://github.com/buildtesters/buildtest/blob/devel/.github/workflows/black.yml and it is using the @stable version
Just to prove it i am going to run black on my code-base and it got not...
Description
Latest actions/checkout is V3 [ v3.3 is most recent ]. Therefore updated the example so people copying/pasting use the latest version.
Reference: https://github.com/actions/checkout
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Description
Resolves #2783
The issue was partially resolved by #2820, but only for cases where the inner class body ends with a definition (class or def) and is followed by another definition. This change enforces a blank line after any nested class with a body (other than just ...) in stubs, particularly those ending with or followed by an annotation for an attribute.
I had to make a slight change to EmptyLineTracker.previous_defs in order to not put a blank line after t...
Is this related to a problem? Please describe.
I believe that the documentation for compatibility with isort may be outdated. The Why those options above? section states:
Black wraps imports that surpass
line-lengthby moving identifiers into their own indented line. If that still doesn’t fit the bill, it will put all of them in separate lines and put a trailing comma.
...
Something that perhaps could be improved is not adding extra empty lines before the # endregion comments:
Current behaviour is as follows:
@@ -16,20 +16,24 @@
class MemberRanking(BaseModel):
guild_id: int
rank: int
score: int
user_id: int
+
+
# endregion
Meanwhile, in my opinion, something like below would work better:
# region Spam
class Foo:
pass
class Bar:
pass
# endregion
_Originally ...
Description
This updates the documentation regarding isort compatibility, as described in #3565.
(Closes #3565)
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
SGTM - Both make sense ...
I'm not sure if lowercase is the better decision, so I'm filing this feedback for discussion.
Reasons to favor lowercase:
-
repr()uses lowercases:>>> "\x1B" '\x1b' >>> "\u200B" '\u200b' >>> "\U0001F977" '\U0001f977' -
I sampled 500K files from our codebase, lowercase is bit more popular (the count below is the total number escape sequences in strings):
\xescapes:- lowercase: 440K
- uppercase: 351K
...
Wow - TIL mypy 1.0
(I initially wrote the issue as a bug report, hence the issue template, but it's probably closer to a feature request.)
Describe the ~bug~
Lines that are too long because of trailing comments are handled inconsistently depending on whether they start with a mypy type: ignore directive.
Specifically, lines where the comment begins with # type: ignore are left as they are, whereas other such lines are broken up over multiple lines, which includes lines that contain `# type: i...
Dear Łukasz Langa,
This is for you, since you were the one with the brilliant idea to start this abnormal cell growth that is black. For casual readers and passers-by, please consider that I am 50% black, as my mother is African, so this is no racist talk.
Ford once said about a car he was selling "And you can have it in any colour you like, as long as you like black." I can see why the name, here.
Big organisations all have their own code style. We all heard that MIcrsoft's new de...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Wow.
You can never have enough publicity when trying to reach end users >.<
Before:
with (
mock.patch.object(
self.xxx_xxxxxx, "xxxxxxxxxx", autospec=True
),
mock.patch.object(
self.xxx_xxxxxx, "xxxxxxxxxx", autospec=True, return_value="xxxx"
)
):
pass
with (
mock.patch.object(
self.xxx_xxxxxx, "xxxxxxxxxx", autospec=True
) as a,
mock.patch.object(
self.xxx_xxxxxx, "xxxxxxxxxx", autospec=True, return_value="xxxx"
)
):
pass
with (...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
I accidentally had the following configuration in a project:
[tool.black]
extend-exclude = [
"backendapp/migrations"
]
If i then run black . -vvv, it tells me e.g.
manage.py ignored: matches the --extend-exclude regular expression
which is really confusing because backendapp/migrations is neither a regex nor should it match manage.py.
The solution is extend-exclude = "backendapp/migrations", which i only realized when looking into other projec...
hello everyone! 👋 I've noticed that there is an increasing number of lint/format/build tools that get great performance wins by using Go or Rust under the hood -- esbuild, ruff, and rome come to mind here. I'm curious how you all have thought about using these languages or others for performance-critical code or if there's any ongoing work in this vein already.
Apologies in advance if this is asked a lot -- I did a Discord search in this channel but didn't see much relating to this.
hey
no current plans. We are using mypyc for performance and we'll hopefully make more performance optimizations in the future. A rewrite in a totally different language would be a huge undertaking, beyond the resources available to the team
Thanks for the reply and context! Makes sense, I certainly understand that a team can't pursue everything. Thanks for everything you do on Black, it's a lovely tool.
We're lagging behind on regular maintenance of the project already. Maintainer time is extremely limited so even the rewrite of a small part of the project would likely stall and never see the light of day.
I also don't know Go or Rust. I know some C but I don't think any of us would want to rewrite Black into C 😅
Is there a way to have black format Protocol class definitions like they're stubbed pyi files?
I feel like the question of "rewrite in <insert compiled language>" is going to appear on every runnable project soon. we have such questions in Poetry on a regular basis and the answer is pretty much the same as yours...
"If it's not written in <compiled language>, it must be too slow!!"
out of curiosity, is there "performance-critical code" that you're thinking of in particular?
usually black is rather fast, and i can't imagine what would require it to be faster than it is now
people using it on save with somewhat big files in IDEs complain black's too slow
black in C would certainly be a sight
huh.
there's a relatively easy optimization that we can do to improve formatting performance by 50%, but it means dealing with a lot of edge cases
may look into that eventually
I guess that when they have autosave enabled and it runs every X seconds, it might add up to a delay
which one is that?
turning off --safe?
wait actually I might be wrong, but the forced second pass seems unideal
I just remembered that we probably cut the third pass in the safety check though so it shouldn't have affected performance much.
wait, so black does more than 2 passes?
Hmm, so format_str does two passes if changes are made, and then assert_stable will do one more pass. A long time ago we only did at most two passes.
it's always fascinating to learn how stuff like this works...
According to an user report, Black takes 200ms per 1K LOC
With Rust they claim it would be basically instantaneous.
Yeah we forced one more pass to work around a nasty stability bug with trailing commas and optional parentheses.
I thought we made it so we didn't do the third pass if the second pass didn't change anything? that would be a nice optimization
people then: *computer does stuff* haha, it's thinking!
people now: why do I have to blink to see the result?!
We did not. https://github.com/psf/black/blob/d9b8a6407e2f46304a8d36b18e4a73d8e0613519/src/black/__init__.py#L1079-L1085 format_str does not communicate whether it did one or two passes.
src/black/__init__.py lines 1079 to 1085
dst_contents = _format_str_once(src_contents, mode=mode)
# Forced second pass to work around optional trailing commas (becoming
# forced trailing commas on pass 2) interacting differently with optional
# parentheses. Admittedly ugly.
if src_contents != dst_contents:
return _format_str_once(dst_contents, mode=mode)
return dst_contents```
Seems like a mostly safe optimization though? Not sure how we'd implement it though without breaking API compat.
add a new _format_str_internal function that returns (data, was_changed)
format_str calls it; in format_file_contents we call _format_str_internal
So format_file_contents calls _format_str_internal directly so it can decide whether to call assert_stable?
I guess since we never had safety or stability guarantees for format_str that's fine.
I was referring abstractly to hot code in Black, but I'm not deeply familiar with the project internals or where the hot code might be.
As for the context of my original question, I recognize there's a pretty wearisome crowd of drive-by commenters asking their favorite projects to "Rewrite it in Rust" [https://transitiontech.ca/random/RIIR] and I could have made it clearer that I was asking out of curiosity and interest in contributing to such efforts. I've maintained enough projects to know how frustrating drive-by comments suggesting massive work items can be, and I hope that my question wasn't taken in that spirit
I believe a lot of libcst is a python parser in rust …
And is our likely successor once we stop flogging blib2to3
@austere lava would know more 🙂
<@&831776746206265384> 🤷♂️
!mute 960981532309340180
:ok_hand: applied mute to @mint barn until <t:1676738298:f> (1 hour).
Is this related to a problem? Please describe.
I am running the latest Github action and the latest PyPi black version.
I realize that the Github action can specify which black version to use, but I don't want to maintain that, too.
I would like to add to the logs which black version is responsible to checking my Python scripts.
How can I accomplish that?
Describe the solution you'd like
I tried executing something similar to black --version in a subsequent step but if...
Hi guys, how to make black format tuple and list like this?
CLASSES = (
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner',
'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet',
'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile',
'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain',
'window-blind', 'window-other', 'wood')
Black makes long tuple one item per line.
Hi! I want to apply black formatting on my Python project, including build/ directory which is excluded by default. I tried using --exclude but then .gitignore is ignored and other bad things happen. Is there an elegant solution to my use case?
You can't, Black purposefully does not have many formatting options. You can make Black not format part of the code by using # fmt: off and # fmt: on comments but that means you'll have to format that part manually
exclude has a default value which you can override but you have to ensure that you keep the existing excludes that you care about while removing build/ which you don't care about
The default value of exclude can be found in black --help
The output of that command can also be found here: https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#command-line-options
I'd suggest specifying such options in a configuration file, not as cli arguments so that anyone working on the project gets them when they use Black
exclude is a regex btw
@lament crow , when overriding excludes, .gitignore is ignored. According to the docs it is an expected (and the observed) behavior, but I don't understand why and how can it be unignored (https://black.readthedocs.io/en/stable/usage_and_configuration/file_collection_and_discovery.html#gitignore)
The suggested solution, to use --extend-exclude isn't a good fit for my problem, as I want to remove a value from the default exclusion list
There's no recourse. That's as designed as per https://github.com/psf/black/issues/2164.
Might be better to allow .gitignore to be configured using a flag. Not sure how common either of these use-cases are though.
thanks @bright glacier, I can't say how common it is, but I can say that if you happen to have a build directory that you would want to apply Black on, your life becomes black 😄
If having this feature controlled by an argument is an option, I would be happy to open a pull request for it
You can always pass the files in the build directory to black explicitly.
are there any plans to make something like https://github.com/charliermarsh/ruff-pre-commit to allow usage of the mypyc wheels in pre-commit?
pre-commit builds the package when the hook is in the same repository, but when using a mirror it can download from pypi and instead use prebuilt wheels
Huh, that's weird
I want to, but I haven't pushed for it. It's a bit unfortunate that we have to create a mirror.
Got it. Thank you.
ye, and its quite nice
Describe the bug
I have a monorepo with multiple packages, each package has a pyproject.toml that describe the package and it's dependencies.
I also have a pyproject.toml in the git root with the black config, and I always run black with the --config ./pyproject.toml flag, since I cannot rely on the configuration file automatically resolved by black (see also https://github.com/psf/black/issues/2863 & https://github.com/psf/black/pull/2525)
The problem is that the project root do...
Describe the style change
Currently when run against Jupyter Notebooks, black removes semi-colons. But in Jupyter notebooks, a semi-colon has meaning—it tells the notebook to not print the output from that line (as it normally would by default for the last line in a cell). When writing notebooks for instruction, this can be annoying.
Additional context
An example of where this comes up—note after running black ...
Hello I am trying to use black jetbrains integration. I followed the instructions.
pip install black[d]
Requirement already satisfied: black[d] in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (23.1.0)
Requirement already satisfied: aiohttp>=3.7.4 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from black[d]) (3.8.3)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (2.1.1)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.8.1)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (4.0.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.3.1)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (6.0.2)
Requirement already satisfied: attrs>=17.3.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (22.1.0)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.2.0)
Requirement already satisfied: colorama in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from yarl<2.0,>=1.0->aiohttp>=3.7.4->black[d]) (3.4)
Clicking start gives
return _run_code(code, main_globals, None,
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\\AppData\Local\Programs\Python\Python310\Scripts\blackd.exe\__main__.py", line 4, in <module>
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\blackd\__init__.py", line 13, in <module>
raise ImportError(
ImportError: aiohttp dependency is not installed: No module named 'aiohttp'. Please re-install black with the '[d]' extra install to obtain aiohttp_cors: `pip install black[d]`
have you followed instructions in black's documentation?
https://black.readthedocs.io/en/stable/integrations/editors.html#pycharm-intellij-idea
Yes, uninstalled both black and the extension. Than started from scratch on the instructions. The only difference is I checked "Show changes on potential destructive format changes" or similar.
It's most likely that the path to black you have is not the same black installation that you installed while following the instructions
assuming you ran the pip install command exactly as shown in the instructions, can you show the output of pip --version
I am not at my PC rn. This is likely true. I remember that when running pip list black was shown but no black[d] is this normal?
My pip version is 22.1 but I think you meant blacks version?
I wanted the output
aside from version it also shows the path
which is what I cared about here
Would it make sense to install black[d] globally instead of on the venv? Than it would be easy to get the right path.
But I'm not at my PC rn so I will have to try it later.
You're not pointing at the executable in a venv here
Ok, I will uninstall and reinstall globally that should fix it. Or at least make it so I can manually tweak the path a bit.
Thank you
Description
This PR removes the Dockerfile as it is not required for the use case of this fork. The Dockerfile is used to define the environment and dependencies for a Docker container. However, as we do not plan to use Black in a Docker container, we can safely remove this file.
Checklist
- [x] Add an entry in
CHANGES.mdto inform users about the removal ofDockerfile - [ ] Add / update tests if necessary
- [ ] Add new / update outdated documentation
By removing...
^ is apparently what they're working on
Huh.
why are you hiding your username if you send it in next message? 🤔
just curious
I'm gonna guess it's a $corp wanting to maintain a fork for their needs?
maybe? I didn't look too deeply but it didn't sound too corporate, e.g. there are Discord links for the authors
and they deleted all the docs
Very weird.
Describe the style change
Black will sometimes split the .get() function for dictionaries in a not so easy to read way.
Interestingly, it will also sometimes split it in an acceptable fashion, depending on the length of the line and/or components of the line.
Examples in the current Black style
Both of these are not great:
a_dict = {}
for _ in a_dict.get("some_really_long_key_name_to_make_this_line_too_long", {}).get(
"another_key", ["defa...
I'm trying to use Black with vim but I'm getting this error...I see that the vim script is trying to use a different python...anyway to make black use my pyenv python instead?
nvm neoformat can handle it without the black vim plugin
#3219 (by @stinodego) introduced inference of the target versions for black from the requires-python project metadata in pyproject.toml. However, it was not implemented correctly.
The rules for the comparison operators in requires-python is documented in PEP 440.
For example, >3.7,3.7,3.7.0,3.7.0,3.7,<3.10, so they should give the same results.
I re-implemented the inference code. I will open a pull request as soon as I ...
I'm a little unsure whether to categorize this as a bug or a code style issue, but anyways...
Describe the style change
This is so incredibly specific that it is best explained by example. [See this example in the Black playground](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4APwAZNdAD2IimZxl1N_Wg0-BMH4fcUYMwHKasLaVw7xjM4QyvB9osUuBElnz-G2ZEZpSYF021RLKk2Djz2UGfzFYxq26zXcKWaR0kUNdvmjlTbSVkRztHcjhMlUGtW8TefjIZLqWV1sGvFaxaQH1s4UXgBcZaaQm0uah3SwdDjpptgH...
Fixes #3581.
The old algorithm checked, for each target version 3.X, whether 3.X (which is roughly the same as 3.X.0) is contained in a version specifier that was modified from the requires-python project metadata to be less strict regarding patch versions. One problem of it was that, for a requires-python value of ">3.X" (which means the same as ">3.X.0"), it concluded that target version 3.X is not supported although Python versions >= 3.X.1 are included in the version specifier. I f...
Tests fail against setuptools 67.3.0:
==================================== ERRORS ====================================
____________________ ERROR collecting tests/test_blackd.py _____________________
tests/test_blackd.py:11: in
from aiohttp import web
/usr/lib64/python3/site-packages/aiohttp/__init__.py:212: in
from .worker import GunicornUVLoopWebWorker, GunicornWebWorker
/usr/lib64/python3/site-packages/aiohttp/worker.py:11: in
from gunicorn.config import Acces...
Description
https://setuptools.pypa.io/en/stable/history.html#v67-3-0
Added deprecation warning for pkg_resources.declare_namespace.
Users that wish to implement namespace packages, are recommended
to follow the practice described in PEP 420 and omit the
init.py file entirely.
However, projects (for example, zope) may use pkg_resources's namespace. This warning can be ignored.
Describe the bug
Black doesn't fully honor #fmt:off on line before #fmt:on, it moves comments.
To Reproduce
lambda_fields = {
# fmt: off
"full_name": lambda x: x.display_name,
"publication_status_as_label": lambda x: x.professional_validation_workflow.get_publication_status_display() if x.professional_validation_workflow else None, # NOQA: E501
"transition_state": lambda x: x.professional_validation_workflow.transition_state if x.profes...
Description
Fixes #3572
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Describe the style change
Black will use the brackets of a dictionary key reference to split a line, which is silly.
Examples in the current Black style
def some_func():
message = {}
for _ in range(0, 10):
message["xxxxxxxxxxxxxxxxxxxxxxxxxxx"] = response["ResponseMetadata"][
"RequestId"
]
Desired style
def some_func():
message = {}
for _ in range(0, 10):
message...
Two nits, and a question about async with.
#3489 wraps multiple context managers in parentheses when targeting Python 3.9+, but async with statements aren't handled.
We noticed this in the review of #3589, but the fix is different enough that I'm filing a separate issue and will send a follow-up PR.
Is your feature request related to a problem? Please describe.
This is a similar to but not exactly the same situation as in https://github.com/psf/black/issues/3576, where black's current behavior causes the inferred project root directory to be the file system root directory (/), which makes it difficult to set up exclude paths in black's config file.
In our situation, we also have a multi-language monorepo with multiple pyproject.toml-based Python packages, but we also have...
black is formatting -2**3 as -(2**3)
why?
>black -c "-2**3"
-(2**3)
>black --version
black, 23.1.0 (compiled: yes)
Python (CPython) 3.11.0
it is a bit weird IMO
so you don't think it's (-2)**3
in math when you write -a^b it always mean -(a^b)
i think it is obvious enough that -a**b mean -(a**b) and not (-a)**b
i dont like this behaviour 😔
I don't think it's universally true across languages though it is common. But either way, my first instinct is that unary operators bind most tightly (and in some languages aren't treated as operator during parsing but rather a part of the number) so even if mathematically it makes sense, I wouldn't be sure that this is how Python behaves. It all comes down to avoiding a potential confusion point.
I hate GHA sometimes..
what happened?
interesting
ooh i noticed something else
do you mind if i make a pr?
go ahead
Looks like there is an Actions outage: https://www.githubstatus.com/
Welcome to GitHub's home for real-time and historical data on system performance.
@tight bone btw i know you do a lot of ci troubleshooting, any ideas?
That explains why everything GHA seems to be broken.
thanks, apparently its an outage @tight bone
Had the same issue a couple minutes ago, so yea :/
Is your feature request related to a problem? Please describe.
Right now, if a file parsing because of invalid type comments (even if the code runs just fine), black won't format the file.
For example:
import typing
def foo(
# type: typing.List
bar,
):
print(bar)
foo(10)
While the code still runs:
$ python3 asd.py
10
Black no longer formats it:
$ black asd.py
error: cannot format ...
Why type comments are still supported?
I thought they are useless since annotations exists
Mypy is also raising SyntaxError if there is invalid #type:smth inside code.
It happens very often to me when i comment big parts of code, because annotation type: smth becomes #type: smth and it is invalid type comment
yeah on mypy's side we have talked about deprecating them. note though that # type: ignore counts as a type comment and that's still important
def f(
type: type[int],
) -> int: ...
# after commenting out it becomes this:
# def f(
# type: type[int], ## <- this is a syntax error, very annoying
# ) -> int: ...
I never thought about # type: ignore like a type-comment, that's interesting
#black-formatter message
after nearly two years, I can now say this codebase is formatted with black.
Description
Resolves #3593
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
:incoming_envelope: :ok_hand: applied mute to @mint barn until <t:1678059817:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).
The <@&831776746206265384> have been alerted for review.
Describe the bug
A file containing a line with type: in a comment block breaks black.
To Reproduce
- create a python file with the following content:
# this is a test
# type: foo
# breaks it
def foo(a, b):
pass
(note double space between function parameters to cause black to reformat)
- run black:
$ black broken.py
error: cannot format broken.py: cannot use --safe with this file; failed to parse source file AST: invalid syntax (, li...
Describe the style change
I'm not sure if this is intended or not, but I noticed that sometimes in Black >=22.12.0 a trailing comma will trigger wrapping the concatenated string in parens, which otherwise wouldn't take place (if there was no trailing comma).
The suggestion is to make it so that the presence of the trailing comma would have no bearing on whether the concatenated string will or not be wrapped in parens.
PS: In this particular case the trailing commas are added's by...
@vale heron 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
I have some code that uses one of a few different files. So I'm commenting out certain lines to switch between files.
But the combination of Path, /, and a commented out line results in incorrect behaviour.
Workaround is to put a comma at the end of the line.
Black https://github.com/psf/black/commit/4a063a
[Playground link](https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AD8AJddAD2IimZxl1N_WlsgJGL5Th9rwn0ffOInnwH3UJGLFUg2uan3GmixKnBQYx-AdWcO8...
!e [3.10] <print("You Are Hacked!")>
<@&267628507062992896> How To Check Code?
!e
code
!e code
@slim stirrup :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | code
004 | NameError: name 'code' is not defined
@slim stirrupthis channel is for the black formatter project; please go to #bot-commands
oh wow
That moment when you throw your code into black, and it just spits out the exact same thing!
feels nice
Description
Corrected a few spelling mistakes I identified using Codespell within documentation and tests.
Checklist - did you ...
- [X] Add an entry in
CHANGES.mdif necessary? - [X] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
Is this related to a problem? Please describe.
Describe the solution you'd like
Describe alternatives you've considered
Additional context
hello ?
yes?
what is this
Read the channel topic
i now but what is the project about
ok thanks
My environment is: python = 3.11.1, black = 23.1.0
the following is the info of commandpoetry show black:
name : black
version : 23.1.0
description : The uncompromising code formatter.
dependencies
- click >=8.0.0
- mypy-extensions >=0.4.3
- packaging >=22.0
- pathspec >=0.9.0
- platformdirs >=2
The code that black failed to skip:
join(
packages,
func.coalesce(ord...
I'm curious what are black devs thoughts on changes that https://github.com/google/pyink makes. I know some changes that have been upstreamed already, but the point 1 and 3 in the readme are ones that have pushed me away from black historically.
(I guess maybe also 2, but I suspect that one will be very controversial :)
2 and 3 are not things we're willing to change. 1 would be good to have though
1 makes me think of https://lukasz.langa.pl/36380f86-6d28-4a55-962e-91c2c959db7a/
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Pyink maintainer here. Adding to what Jelle said, I plan starting to upstream (1) in the coming weeks. No plans for (2) & (3).
Describe the style change
It's possible to have line wraps in the body of a lambda if the lambda expression as a whole is parenthesized, or used in contexts such as function arguments. Currently black would give the wrapped lines the same indent as the line that lambda is on, which could cause confusion. I propose to have black automatically parenthesize the lambda's body so it could be further indented.
Examples in the current Black style
some_func = (
la...
Is your feature request related to a problem? Please describe.
Black will currently not reformat this:
from typing import Union
a: int|float = ...
b: float|int = ...
c: Union[int, float] = ...
d: Union[float, int] = ...
which leads to some messy code when the type list gets long, but clearly the order of the types don't matter and might as well be sorted. I just had a git diff that was completely unnecessary, and it makes it harder to see if two somewhat complex...
Describe the bug
Using multiple # fmt: skip in the same expression causes an INTERNAL ERROR.
To Reproduce
The first example (a) works but all others fail:
a = (
"this should " # fmt: skip
"be fine"
)
b = (
"this is " # fmt: skip
"not working" # fmt: skip
)
c = (
"and neither " # fmt: skip
"is this " # fmt: skip
"working"
)
d = (
"nor "
"is this " # fmt: skip
"working" # fmt: skip
)
e ...
Description
Fixes #3591
In addition, other formatting to non-async version of the corresponding statement is also applied, such as removing unnecessary parens.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Looks good, thanks! (apart from two minor things I commented)
Description
Fixes #3438.
This isn't put in preview style because:
- Already formatted code always has the extra blank line, so it shouldn't change already formatted code and doesn't violate the stability policy.
- This unblocks us from upstreaming the incremental formatting patches in Pyink, and we don't want to require
--preview(in at least in 2023) to use this feature. It would also make integrations with IDEs / pre-commit harder if we require--preview.
##...
Hello, I just hear of this project so I installed to test it, following the usage indication on some file I got this

I installed it like pip install ruff
ruff version: 0.0.256
Python version 3.11.2
OS: Windows 10
i wonder how they found their way to the black issue tracker from ruff
Guyssss, how do I skip check for one line in Black?
# fmt: skip on the end of the line
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
268dcb6 Do not add an extra blank line to an import lin... - yilei
Thanks for your continued work on Black :)
hm tests are broken on main
Seems to be a bad interaction between changes from #3563 and #3610, cc @yilei and @WMOkiishi. I don't have much time right now, so I am going to change this test for now so CI isn't broken, but ideally we'd preserve two empty lines here.
i dunno, i don't work on black
I'll take a look at that PR tomorrow Jelle. I need sleep.
self.previous_defs[-1] is now a Line not the int depth.
This should fix the bug introduced for blank lines
thanks, merging it now
I wanted to take a look because this PR falls back to using the built-in ast module even on Python 3.7 which we avoided doing previously, but that's a really minor edge case — so it's fine. All it might do is make some files with invalid type comments still unparsable.
53c23e6 Support files with type comment syntax errors (... - tusharsadhwani
3a9d6f0 Bump myst-parser from 0.18.1 to 1.0.0 in /docs ... - dependabot[bot]
5c064a9 Bump sphinx from 5.3.0 to 6.1.3 in /docs (#3499) - dependabot[bot]
I didn't check the width table code too closely since I presume that they were borrowed from rich. Everything else looks good though. Many thanks for the PR!
ef6e079 Let string splitters respect East_Asian_Width... - dahlia
hey where does black store its cache?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
Running black with a pyproject.toml, where "extend-exclude" is set to ignore a specific file dose not work and the file is formatted when black is run.
To Reproduce
Make the following Dockerfile:
FROM mcr.microsoft.com/vscode/devcontainers/base:0.203.5-bullseye
RUN apt-get update && apt-get install -y python3-pip
RUN pip3 install --no-cache-dir black==23.1.0
WORKDIR /
RUN git init black-obs
WORKDIR /black-obs/
RUN git branc...
Describe the bug
from atmodata.iter.tensor import (
ThBatchInterleaver,
ThConcatter,
ThSplitter,
ThToDevice,
)
gets formatted to
from atmodata.iter.tensor import ThBatchInterleaver, ThConcatter, ThSplitter, ThToDevice
despite trailing comma.
On a side node: # fmt: off gets ignored.
Expected behavior
Leave my code alone if I'm specifically asking for it.
Environment
- Black's version: 23.1.0
- OS and Python ve...
Hey I don't have single knowledge of git hub can you tell me how and where I can learn about GitHub
Hello,
I did not dive into the issue but this can still help, so here is what happens:
I use tox to run black, mypy and unittest.
I have dataclasses with several arguments. One of the arguments was commented and was named type, such as:
@dataclass
class A:
first: int
# type: int
Even though it was commented out, I have the following error message:
error: cannot format ..../.../: cannot use --safe with this file; failed to parse source file AST: expec...
Describe the style change
If a literal string consists of multiple smaller strings concatenated via adjacency, then prefer to place each smaller string on its own line.
In Python "abc" and "a" "b" "c" are two identical strings. However, developers typically prefer the first style, as it is shorter and has less visual noise. Then, the only situation where the second style might be useful is if you want to juxtapose strings vertically:
"a"
"b"
"c"
Right now, ...
Describe the style change
If a function takes a single argument which is a list, set, dict, or string, then the delimiters for those expressions can be immediately adjacent to the function's parentheses.
This would save both horizontal and vertical space, while also improving readability.
Examples in the current Black style
foo(
[
100,
200,
300,
]
)
bar(
{
"alpha": 1,
"beta": 2,
"gamma": ...
Describe the bug
We are using latest black 23.1.0 and it is putting .format after string making line longer than required.
Solution is to use experimental-string-processing however it will probably be removed due to its functionality moved to future.
However the problem is that future contains also other improvements and we don't want the style to change with each black upgrade.
To Reproduce
Black configuration:
[tool.black]
line-length = 120
target-version = ['py...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Just checking, any chance there will be a new Black release soon?
yes I should do that. going to aim for end of this week
Thanks! Let me know if there is anything I could help.
(We need a new version for a change in blib2to3)
For anyone who is paying attention here, just an FYI that I've stepped away from maintainership of Black for the time being. I'll be around to help out with anything that may be within my domain (CI/automation/docs), but I'm not actively following Black's development any longer.
thanks for all you work on Black! Your mypyc work made a huge difference to performance, and diff-shades made it so much easier to evaluate proposed style changes
I should probably get https://github.com/psf/black/pull/3508 in too
Description
See 'How to fix` in #3507
Checklist - did you ...
Add an entry in CHANGES.md if necessary
Add / update tests if necessary?
Add new / update outdated documentation?
Black https://github.com/psf/black/commit/f3b1a3 back break an expression when it's an argument to a function with comments inside the call.
Options
--line-length=88
--safe
--target-version=py310
Input
def task(self):
self.retry(
# 1 minute
# 2 minutes
# 4 minutes
# .. up to 2048 minutes (34h more or less)
countdown=60 * 2**self.request.retries
)
Output
def task(self):
...
Describe the bug
Black hangs indefinitely trying to format a file with ridiculously long nested dicts. I presume it does eventually complete the task, but I haven't left it long enough to see how long that would actually take.
To Reproduce
- Copy and paste this file into a
.pyfile: repro.txt - Run black on it
- Wait
Expected behavior
This is very odd code, so I don't necessarily expect black to be ...
Congrats! 🎉
Describe the style change
Examples in the current Black style
from typing import Sequence
very_very_very_very_very_very_very_very_long_expression = 'foo'
if isinstance(very_very_very_very_very_very_very_very_long_expression, Sequence) and not isinstance(
very_very_very_very_very_very_very_very_long_expression, str
):
print('foo')
another_very_very_very_very_very_very_very_very_long_expression = False
if (
very_very_very_very_very_...
Description
This PR aims to move the SECURITY.md file from the root of the directory to the .github/ directory. Github looks for a security guideline file in the following order: .github dir > project root > docs dir (source). Moving the file to the .github/ dir leads to a minimal project structure without any functional change.
C...
any way format from a line to line into a multiline, based on length?
this for functions but also other types of constructs
e.g. something like this - (to be more compact)
input
training.train_regular(
"cpu",
world_size,
config["Processing"]["data_path"],
config["Job"],
config["Training"],
config["Models"],
)
output
training.train_regular("cpu", world_siz...
Description
This PR aims to minimize the number of configuration files for the project. Instead of a separate .coveragerc and mypy.ini, we now would have all the configurations within the pyproject.toml file leading to a overall minimal code structure.
Checklist
- [x] Add an entry in
CHANGES.mdif necessary? (skip news??) - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
it just reads the file and has a list of mistakes, then if it sees one of those in your code it will re-format it i'm guessing
I found an issue in the current version of black where line wrapping is not correctly applied. This does not involve string reformatting.
Black v23.3.0
Yes
Does installing black[d] implicitly install black as well? I've always installed both via pip so far, but my IDE is now stating that black is redundant with black[d] present
yes
Thank you
Also found out that I can merge package extras as psycopg[binary,pool], nifty stuff
Is psf/black#2787 still needed?
Description
As titled
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
96ee2fe Bump furo from 2023.3.23 to 2023.3.27 in /docs ... - dependabot[bot]
a552f70 Fix an example for 'Improved parentheses manage... - harupy
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Code before:
def asdf_asdf_asdf_asdf_asdf() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None:
pass
Black formatted to:
def asdf_asdf_asdf_asdf_asdf() -> (
my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None,
):
pass
The trailing comma is incorrect, see [playground](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADcAH1dAD2IimZxl1N_WlbvK5V8JNI78iDZsHigDVyj...
An unusual but valid variable name (Ø) in linegen.py .
When using pipreqs, a popular tool (5K+ ⭐) for generating requirements.txt files, it is causing issues because for some reason it is unable to parse the variable name.
Although the issue is not in black, and I have filed a related bug report in the pipreqs repo, using an unusual va...
The black formatter just formatted the pygame argument in this way. Maybe I am biased but I find this style of formatting less readable…
I am open to discussion
What do you think is more readable?
None of the above?
Description
This reverts the change in #3307, as the changes that would have been introduced in the 2024 style are too destructive based on feedback. See https://github.com/psf/black/issues/2188#issuecomment-1489053232.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Is this related to a problem? Please describe.
The Version control integration briefly mentions black-jupyter:
The
black-jupyterhook is only available from version 21.8b0 and onwards.
Also, searching the docs for it, barely anything comes up. To figure out how to use, I came upon this: https://github.com/psf/black/blob/23.3.0/.pre-commit-hooks.yaml
And som...
Short question about black: I use the option --no-color but black's output is still colorized. Especially the blue characters are difficult to read on the black background of my terminal. How can I switch off colorized output of black altogether?
Looks great ofcourse, but I don't need this.
And I can't read it
Based on the documentation of that option, it only determines whether Black returns a colored diff or not (when --diff is used).
If this is something that Black maintainers want to change, this should, presumably, be as easy as setting ctx.color (ctx being click.Context) to the value of color flag
So, no option to have black suppress colorization. 👍 I'll see what I can do in the CLI to strip ANSI-codes.😞
Describe the style change
Examples in the current Black style
s1 = (
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
'bbb"bbb"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
)
s2 = (
'aaa"aaa"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
)
formated to (black --preview test.py):
...
This model is a decision tree classifier that predicts whether a person will buy a car or not based on their age and income.In this example, the X array contains the input data, which consists of age and income values for eight different people. The Y array contains the corresponding output values, which indicate whether each person bought a car or not.
The decision tree classifier is created using the DecisionTreeClassifier class from scikit-learn. The fit method is then called to train t...
that seems.. very random
some things we are not meant to understand
I filed relevant mypyc bug here: https://github.com/mypyc/mypyc/issues/990
This is an error only in mypyc 1.0.0+
I want to be able to specify the default files within the configuration file so that I don't need to duplicate this config in different places.
[tool.black]
files = ["src", "scripts"]
Then it is possible to invoke black without passing any paths:
👉 black
yada yada yada ✨
I made a tool that makes Python CLI tools start much faster. With it, I can run black on a few files in 10-20ms on my laptop, vs. at least 120ms for the mypyc-compiled version. Especially great when combined with pre-commit in git pre-commit hooks.
Happy to get some early adopters checking it out!
https://github.com/taleinat/jumpthegun
That sounds awesome, thanks! Do you have any resources on how it works? I assume it starts some sort of server that caches the process so you don't pay import costs every time. Some concerns I would have are: does it work on all OSes? what if memory usage from the cached process grows too large?
Hi Jelle! I haven't written anything about how it works yet. I'll add more documentation at some point.
Indeed, for each CLI tool, JumpTheGun runs a background daemon which loads Python and does the imports in advance. This is run the first time the tool is run via JumpTheGun. It stays running until the tool hasn't been run for a while (4 hours by default).
To stop the daemon, run jumpthegun stop <tool-name>, or just kill the daemon process.
Describe the style change
Black treats standalone expressions containing boolean operators differently from those containing other operators.
Examples in the current Black style
This code is unchanged by Black:
# before and after
foooooooooooooooooooooooo and barrrrrrrrrrrrrrrrrrrr and bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzz and quxxxxxxxxxxxxxxxxxxxxxxxxxxx
def f():
foooooooooooooooooooooooo and barrrrrrrrrrrrrrrrrrrr and bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzz and qu...
math.infis afloat, butbracket_depthisint. Alternatively we could use a really large int for maximum.- The
Finalinnodes.pyis the same as #3645
Btw, any instructions how to build the mypyc wheels locally in the same way as CI? I only manually compiled the files excluding the ones excluded in pyproject.toml.
FYI please feel free to CC me for anything mypyc related. I'm on the mypy(c) core team and I'd be happy to help!
Since you are already here, how can I build the Black mypyc wheels locally in the same way as CI?
Just realized I hadn't answered all of your questions...
- JumpTheGun works on Linux (tested on Ubuntu 20.04) and macOS.
- Memory usage should not balloon over time, since each invocation forks a new dedicated sub-process. (If the processes never terminate, that would cause memory usage to grow over time regardless of JumpTheGun.)
I can help with that, I did it recently. IIRC it basically consists of pip install cibuildwheel and then running it. Let me look up the details.
So looks like I did the following to build a mypyc-based wheel only for my local Linux machine:
0. Have Docker installed, the Docker daemon running, and permission to run the docker cli.
- Create a venv and run
pip install cibuildwheel cibuildwheel --platform linux --helpcibuildwheel --platform linux --print-build-identifierscibuildwheel --platform linux --only cp310-manylinux_x86_64pip install ./wheelhouse/black-22.12.1.dev37+g18fb884-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Thanks! This worked.
Thanks Tal. I've never actually used CIBW locally. (anyway CIBW is amazing <3)
Are you planning to support Windows?
Not initially, since both forking and bash don't work on Windows.
Describe the bug
I've run across an issue where the following code gets formatted not very nicely. This particular snippet should IMO already satisfy Black with line_length=120.
def main(
client: AppRole,
role_name: str = Option(..., help="The name of the role to generate a secret ID for", metavar="ROLE_NAME"),
secret_id: str | None = Option(
None,
help="A custom secret ID to use. If not specified, one will be generated.",
metavar="...
Hello everyone, is it possible to somehow start Black immediately automatically, that is, when I start PyCharm, does it also start in a separate terminal?
Description
Closes https://github.com/psf/black/issues/3641.
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
I locally built the docs and saw it looked fine.
Looks good, thanks! @MarcoGorelli any feedback?
What are you trying to achieve? Do you want black to be run (repeately, automatically) on your code as you edit files?
I'll just share this here, here's my current preferred way to have black (via pre-commit) run automatically on code changes in PyCharm Professional via its "File Watchers" feature:
Thanks
Describe the style change
When assigning multiple similar values with different-length variable names, aligning the = (assignment) operators using spaces should be allowed. In my opinion, this allows the reader to assess the differences in the literals (or function calls) more easily than when the = are scattered over different columns.
Examples in the current Black style
#!/usr/bin/env python3
"""
VT100 escape sequences for text foreground color
"""
black ...
Minor doc update for https://black.readthedocs.io/en/stable/guides/introducing_black_to_your_project.html:
some online Git-repositories like ... do not yet support ignoring revisions ... This is however supported by GitHub currently in beta.
I think this feature is generally available and not beta anymore
black doesn't enforce some sort of an opinionated docstrings format?
You can run black as a daemon. First install black[d] via pip and install the BlackConnect plugin via pycharm. Access it under Tools > BlackConnect and set your preferences as well as run it
import os, json, math, csv, fasttext, nltk, spacy, subprocess, copy, random
import pandas as pd
import numpy as np
import os, json, csv, fasttext, nltk, spacy, subprocess, copy
why didn't black put each of these on different lines?
and remove duplicates?
Does anyone use Black on Airflow DAG files?
I'm guessing the duplicates are there because while an import should be idempotent it doesn't have to be?
I guess
For an Airflow DAG I'm non-plussed by the many lines of graph setup that went from:
[
dataset_service_tablename_A_ready_sensor,
dataset_service_tablename_B_ready_sensor,
dataset_service_tablename_C_ready_sensor,
] >> prepare_cluster >> [
parallel_job_on_A,
parallel_job_on_B,
parallel_job_on_C,
parallel_job_on_A_and_B,
parallel_job_on_B_and_C,
]
to
(
[
dataset_service_tablename_A_ready_sensor,
dataset_service_tablename_B_ready_sensor,
dataset_service_tablename_C_ready_sensor,
]
>> prepare_cluster
>> [
parallel_job_on_A,
parallel_job_on_B,
parallel_job_on_C,
parallel_job_on_A_and_B,
parallel_job_on_B_and_C,
]
)```
It's mentioned that --preview has some cases where parenthesis aren't added… but this doesn't seem to be one of them
The extra indentation makes it stand out next to lines like:
cleanup_cluster >> send_message
cleanup_cluster >> [validate_A, validate_B] >> update_status
Is there any way to influence how Black wraps long boolean expressions (chains of and/or)?
I think it formats this extremely awkwardly here:
# Before
return (
self.file >= other.file
and listify(self.version) > listify(other.version)
)
# After Black:
return self.file >= other.file and listify(self.version) > listify(
other.version
)
Why would Black line-break inside a parameter list when it could instead break on the and?
If I add a third condition to this expression (like and fooz == baz) it will format it how I originally did. Is there any way I can influence Black to do this sooner, like a trailing comma can do for dicts and argument lists?
Maybe it should keep input expression parens. IDK there's probably cases were removing excess parens also looks better.
PEP-597 added an option to warn when the encoding argument to open() is omitted and the default locale-specific encoding is used, because this can cause bugs when the locale is incorrectly assumed to be e.g. utf-8, which may not be the case on Windows, or various systems in e.g. Japan.
Setting PYTHONWARNDEFAULTENCODING=1 in CI, and fixing any existing issues, will ensure that downstream projects can also adopt this check without awkward workarounds.
Describe the style change
The blank lines between a function's definition and its docstring currently get removed by Black. However, it does not do the same thing for classes.
Current Black changes
def f():
"""The line above gets removed."""
return 0
becomes
def f():
"""The line above gets removed."""
return 0
but
class C:
"""The line above stays."""
is not modified by Black.
*Desired style...
:x: failed to apply.
black doesn't touch imports. use isort or ruff for import management
Describe the style change
In a multi-line function-call expression, where each parameter is on its own line, it would be great to add spaces around the = signs.
Examples in the current Black style
some_function(
param1="string value",
param2=1 + 7 + 11,
param3=[
"one",
"seven",
"twelve",
],
param4="another long value",
param5=some_other_function_call(*args),
)
Desired style
some_function(
param1 ...
Description
Hi! It looks like you have some special handling for # type: ignore comments to avoid moving said comments around due to positional meaning. I think this same special handling should also apply to # pyright: ignore comments.
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Describe the style change
After 12 spaces (3 tabs), the assignment of a long string into a dictionary key will split the dictionary and key with new line. This will mostly happen in a class method (example below).
To reproduce:
- add 12 spaces (3 tabs) in front of a dictionary value assignment
- assign a long string that will exceed 88 line length limit
Original Code (take a look on line with (context["header"]))
class DjangoViewsClass(TemplateView):
...
Describe the style change
Strange indentation of a long assert statement, in --preview (it works correctly in the stable branch).
Examples in the current (preview) Black style
assert (
result
== "Lorem ipsum dolor sit amet,\n"
"consectetur adipiscing elit,\n"
"sed doeiusmod tempor incididunt\n"
)
Desired style
assert result == (
"Lorem ipsum dolor sit amet,\n"
"consectetur adipiscing elit,\n"
"sed ...
It seems I misinterpreted this channel as discussion on style choices or unexpected changes
That's a reasonable use for the channel. But discussion of style choices can be kind of endless, so our answer might just be "Black will keep doing what it's doing"
It currently looks like a place to catchup on issue updates… or maybe get some help in usage? I just want to be sure I understand the meaning of "the development and usage of the tool"; whatever works for the primary users.
You can talk about pretty much everything related to Black so that would include things like why Black chooses some style, development, usage, issues people encounter, features they want. Some of these things often make more sense as a trackable Issue on GitHub but there's no a solid line between them
You only have seen issue updates here recently probably because there wasn't much to talk about. I think Jelle is now the main active maintainer so he doesn't have to talk with say, ichard, about Black that often
Describe the bug
Multi-line short raw strings do not get merged properly into a single string.
To Reproduce
For example, take this code:
x = (
r"first "
r"second"
)
The resulting string is:
x = r"first " r"second"
Expected behavior
x = r"first second"
Environment
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
To Reproduce
Unsure, but happens to me consistently with the following:
- start blackd
> blackd --bind-port 45484
blackd version 23.3.0 listening on localhost port 45484
- Send some format requests (here we sent heaps of requests, only two came back, the rest just hung on the connection.)
> blackd --bind-port 45484
blackd version 23.3.0 listening on localhost port 45484
INFO:aiohttp.access:127.0.0.1 [28/Apr/2023:00:03:22 +0000] "P...
Describe the bug
When using """ """ to define multi-line strings, I've noticed that if the user indents with tabs, black seems to replace each additional indentation beyond 1 tab with too many spaces.
To Reproduce
For example, take this code: (sorry about the , code blocks in Markdown don't seem to like tabs, ironically enough). If you replace each with a tab set to 4 spaces for example, you will be able to reproduce this issue.
def test():
"""
Test of indent...
Does anyone have an argument script for winning space-over-tabs by arguing tabs are anachronistic metal things on a teletype and have little place left in files (other than formats like tsv)?
OK, let's change this back for now.
e712e48 Do not wrap implicitly concatenated strings use... - yilei
I don't because in an ideal world I think that tabs actually are actually better about a lot of things, it's just that this doesn't matter because it's more important to use the usual code style for your language of choice. And as said, tabs are better in an ideal world and we don't get to live in one. For example, some of the advantages of tabs can also be disadvantages - the ability for every developer to configure tab width as they wish is a very good thing but the problem with that is that this means that different programs may render tabs differently (on single user's computer) and they don't all allow you to configure them to render things differently. For example, it's popular for some software to assume that one tab is 8 spaces, i.e. tabs in terminals were always typically 8 spaces and some of the command-line applications depend on it which makes it hard to set them to render as 4 spaces even if your terminal applications gives you the choice. Spaces don't have such problems since 1 space always has a width of a single character.
tabs are better in a vacuum, spaces are better in practice is basically my point
Its true that if tabs rendered the same in the terminal, an editor or ide etc they'd be a non-issue and a byte-savings. But they were intended to move the print head to the next bit of movable metal tabstop, so they're intended to be configurable.
if they actually were configurable then that would be fine
my point is that they aren't
not everywhere
Black enforces that every comment starts with a space, except if the comment starts with a hardcoded list of black.comments.COMMENT_EXCEPTIONS (COMMENT_EXCEPTIONS = " !:#'"). These were added over time to support particular tools that treat certain comments specially. We occasionally get requests to treat more comments specially (#3557) or confusion because of the inclusion of particular characters (#3036). I am opening this issue to focus the discussion and arrive at an overall solution....
I think that's enough closed issues for today
That explains why my email is blowing up (yeah I'm still watching the repository).
that's one more month where the issue count went down!
that's kind of depressing, I only made up for one month of growth?
every now and then i close like a dozen mypy issues. but mypy’s net issue growth is still like 30/month
sounds like I should join in for an evening of issue tracker spring cleaning :)
anyway, you also dealt with this month's growth too so you've closed more issues than it may appear on that chart
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Description
I followed the docs to make Black format my %%writefile blocks, but in blind copy-pasting I realized %%writeline was a nonexistent magic (and it was probably meant to be %%writefile).
See the full list of built-in magics: https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-writefile
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [x] Add new / update out...
Hello! Our team have the diff black formatting result on each developer env. How we can debug it? And consider what Black rules we should add to pyproject.toml for got the identical result
you likely have different people running different versions
consider setting required_version in pyproject.toml to standardize on a version
we use the latest, also I got different result format at ubuntu host and in docker conteiner
if you really have different formatting with the same version, that's a bug and you should report it. But my experience is that when people report this, they're almost certainly not running the version they think they are running. Setting required_version = "23.3.0" in your pyproject.toml should help ensure that, at least for versions new enough to support that option
Will try in minutes and return with result, looks like you are right
See python/mypy#15174
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Thansk @dense jungle a lot. Your recommendation works perfect.
Where I can got all list of available settings for pyproject.toml ?
I can't find it in doc. ESLint has a perfect description for each rule.
I have a PR to expand that list but it had some weird sphinx errors and I haven't gotten around to finishing it 😦
https://github.com/psf/black/pull/2839/, let me try to get it ready this time
finally got CI green on that, please review!
a07871b Fix new mypy error in blib2to3 (#3674) - JelleZijlstra
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
:incoming_envelope: :ok_hand: applied timeout to @rugged ridge until <t:1683139543:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Any low hanging issues I could help fix over the weekend?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
The following code can not be formatted
with (a,b): # type: something
pass
when run with these arguments:
$ black example.py
The error is:
error: cannot format example.py: INTERNAL ERROR: Black produced code that is not equivalent to the source. Please report a bug on https://github.com/psf/black/issues. This diff might be helpful: /tmp/blk_o04ck2zv.log
Oh no! 💥 💔 💥
1 file failed to reformat.
**Environmen...
Some with statements can not be parsed by black.
They are unlikely to appear in real code, but they are valid python and can be parsed by cpython.
Examples
with (name_2 for name_0 in name_4):
pass
with (a,*b):
pass
None of these examples have a valid __enter__ or __exit__ and should fail at runtime.
black gives the following error:
error: cannot format example4.py: Cannot parse: 1:8: with a, *b:
Oh no! 💥 💔 💥
1 file fa...
Given:
[][1,]
[][(1,)]
😢 Current behavior
No modifications
😲 Desired behavior
[][1]
[][1]
Description
Okay, so basically I think this is a based feature because of the confusing nature of the implicit tupleification of getitem.
(Also it will help with https://github.com/KotlinIsland/basedmypy/issues/418)
Checklist - did you ... know ❓
- [🚀] Add an entry in
CHANGES.mdif necessary? - [🚀] Add / update tests if necessary?
- [📉] Add new / update outdated documentation?
This is the original version of the code:
def one():
def two():
def three():
_zzzzzzz_zzzz_zzzz_zzzz(
...
why in thonny black format is not working?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
when black converts py print(weighted_randint(1, 10, [1, 1, 1, 1, 4,5,6, 1, 1, 1])) to ```py
print(
weighted_randint(
1,
10,
[
1,
1,
1,
1,
4,
5,
6,
1,
1,
1,
1,
],
)
)
Describe the bug
Black is wrapping some type hints when using multi-line string literals.
Any type hint with an argument seems to trigger this.
A bare type hint, e.g. str does not trigger this.
To Reproduce
For example, take this code:
from typing import Final
query: Final[str] = """
SELECT my_column
FROM my_table
WHERE my_column > 1;
"""
And run it with these arguments:
$ black file.py --target-version py311
The re...
Hi friends! Question: my reading of https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#how-black-wraps-lines
Black ignores previous formatting and applies uniform horizontal and vertical whitespace to your code.
// The emphasis on "ignores" is mine.
Is that I should be able to do the following tickery:
- Run black with my default
line-length = 99. This is a no-op. - Run black with
line-length = 30. This will change a bunch of lines. - Run black with
line-length = 99again. That should revert all the changes.
This is NOT the behavior I'm observing. (3) doesn't revert anything.
Any thoughts on this?
The bigger context is that I'm auto-adding a bunch of pyright diagnostic supressions into a codebase with black formatting and trying to make this 2 tools work together.
Yes, this is unfortunately not 100% true. The biggest exception is the "magic trailing comma", where we keep lists that end in a trailing comma exploded on multiple lines.
If you run black -C, you may get closer to your original formatting
Oh gotcha, makes sense. What is -C ?
🙏 thank you so much Jelle, you are always helpful
@dense jungle is there a similar option by any chance for the () adding?
I have this diffs now all around
- run, _, _, expected_side_artifacts = run_with_artifacts
+ (run, _, _, expected_side_artifacts) = run_with_artifacts
no, unfortunately
ideally we should remove parens in cases like that when we don't need them, but it's a slow process
yeah this pyright + black interactions could be better
Thinking about it, it's actually not possible to improve it I think
You will always have the problem that you don't know which line you need to attribute the supression after the re-formatting
@dense jungle one thing I noticed is that -C doesn't respect the [] type comment syntax. I.e. it was not able to undo this
we might have a bug for that already, if not please report it 🙂
👍
@dense jungle exists https://github.com/psf/black/issues/1756
@hollow valley :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_NAME 0 (x)
004 | 4 POP_JUMP_FORWARD_IF_NONE 4 (to 14)
005 | 6 LOAD_NAME 0 (x)
006 | 8 STORE_NAME 1 (y)
007 | 10 LOAD_CONST 0 (None)
008 | 12 RETURN_VALUE
009 | >> 14 LOAD_CONST 0 (None)
010 | 16 RETURN_VALUE
011 | None
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/okuqalinis.txt?noredirect
@hollow valley :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_NAME 0 (x)
004 | 4 POP_JUMP_FORWARD_IF_FALSE 4 (to 14)
005 | 6 LOAD_NAME 0 (x)
006 | 8 STORE_NAME 1 (y)
007 | 10 LOAD_CONST 0 (None)
008 | 12 RETURN_VALUE
009 | >> 14 LOAD_CONST 0 (None)
010 | 16 RETURN_VALUE
011 | None
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/unosodedik.txt?noredirect
Is blib2to3 considered stable?
I’m working on adding structured pattern matching and parenthesized-context-manager support and as part of that effort have proposed forking lib2to3 with some features of bllib2to3 backported to it.
There are questions around just using blib2to3 instead.
See https://github.com/google/yapf/issues/1067 for more info.
Opened after @char101 said it was okay to open a PR for this. Many thanks to them for adding match statement support for yapf!
lib2to3 is no longer maintained, this pulls in a fork of black's b...
it's not a public UI, and we may remove it if we come up with some other parser
I wouldn't be averse to making it into a separate installable project though, if there's interest
Description
Checklist - did you ...
- [x] Potentially closes #3551
- [ ] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
This is an attempt to close #3551 via an option. This is certainly a WIP but I'd like to get feedback before continuing.
- Is the approach via an option what you want to go for? Or do you consider reverting the style change for 2024 (as @JelleZijlstra hinted ...
@dense jungle thank you for the update. I’ve added your comments to the referenced PR.
though thinking more about this, it may cause complexities with packaging/mypyc compilation, so not sure if it would be worth the effort for us
This documentation section Line length shows a config example:
[flake8]
max-line-length = 88
...
select = C,E,F,W,B,B950
extend-ignore = E203, E501
But I have checked flake8, pycodestyle and ruff documents and still cannot make sure what the selected C is.
Description
This PR updates the black github action to display the output of black in the job summary
Checklist
- [x] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Result looks like this:
- erroring with verbosity on
- success with verbosity off
Just checking if we should care about the new lines, I feel it might mess up output people maybe parse and make things harder to read ...
Thanks for taking my suggestions into account. This all looks good to me now to get the nicer summary and does the right thing to stderr output for all platforms :)
Seems we need:
- toml support for coverage
- mypy is very unhappy now showing lots of type errors
- Haven't looked - but are these valid or problem with getting it's settings from the toml?
dc188f2 Bump peter-evans/find-comment from 2.3.0 to 2.4... - dependabot[bot]
ok so another edge case of pyright+black interactions https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AEvAMpdAD2IimZxl1N_WmufDs0LpH-m0u1CYeUiV-mNdcgl9W4yVi-Y_0m71dk3gORdBorNlMpLUC2Q8sVZg-xGpsLzLZpzNyG2KSPeLQvxK9dMpScAOTol1exTdsQ9Xq0zWFnQEA8r_LsvFhxTkkAByrR1yAMeeoxRUjwZ1Q3Pa4ZpzKKZFUb2pwsIUdKXMcuadKspposliL5QS6Kv9zv-XHyH-7shHi3-82uorWknEnXxRFC-GmGItgxbn1Z--qDS1bHaX943n9ikSzmGczAAAACMnFawvW14VgAB5gGwAgAABp_eILHEZ_sCAAAAAARZWg==
with patch(
"xxx"
) as get_firmware_function:
# return_value is unknown param, whatever
get_firmware_function.return_value = "/dev/null" # pyright: ignore[reportGeneralTypeIssues]
This supression is getting messed up by black
Playground for Black, the uncompromising Python code formatter.
Description
I would like to expand the excluded files/folder given in the default value (DEFAULT_EXCLUDES).
I would like to exclude the folders of .vscode, .pytest_cache and .ruff_cache. I tend to add these in the exclude arg of [tool.black] in my project.toml files. I can't see others wanting to run black on these unless i'm mistaken. I'm therefore wanted to upstream my excludes and save potential work for others who add this to configurations excludes.
To make it easier t...
Is it possible to override default max line length just for a module?
Description
Fixes psf/black#3659
Since the psf/black#3035, the blank lines between a function and its docstring are removed. The class docstring is special cased in the code to leave one blank line after, so that change has no effect. This PR fixes that.
BTW, but I couldn't find a test for the function case so I added one just to be sure it doesn't regress :)
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tes...
Describe the bug
When calling a function to get an index for string access. The black formatter adds whitespace after the function call. Which causes a lint error in Flake8.
To Reproduce
str1 = "hello"
str2 = f"{str1} World!"
#Black inserts a space befor the ':' here. Then Flake8 see's that as an issue. E203 whitespace before ':'
print(str2[len(str1):])
#No whitespace is inserted here
print(str2[5:])
And run tox with this config:
commands ...
haven't gotten one of those in a while
Describe the bug
Patterns with trailing slashes in .gitignore are not processed by black, meaning that there is an inconsistency between the files processed by git and the files processed by black. In git, trailing slashes only match directories, but it appears that normalize_path_maybe_ignore does not include trailing slashes for directory paths, leading to this inconsistency.
To Reproduce
Create a directory with the following fi...
I think you can format all except one module with one line length and then format only one module with other line length
true. but you can't do it with one invocation. We got a PR for that but I think we decided against it
Would there be interest in an alternative to blackd that doesn't require modifying black at all, uses a generic protocol and client, and can be used for other CLI tools as well?
yes
Cool! I've been working on something like this for a while, and have recently released it. It works perfectly with black :).
In terms of maturity, it's still early stage, but I already have it integrated into my git pre-commit hooks and IDE file watchers and use it all of the time.
JumpTheGun: https://github.com/taleinat/jumpthegun
I'm super-curious to hear what you think about it @dense jungle !
Relating to #3658, if PYTHONWARNDEFAULTENCODING is set, this library raises a warning at:
Description
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Makes sense to me, as we assume source we parse is UTF8 compatible ...
We only call this with our own files Grammar.txt and PatternGrammar.txt, which are ASCII.
Description
Several new versions of mypyc has been released since the last upgrade, and they include some performance improvements which could make the compiled version of Black run faster.
https://mypy-lang.org/news.html
The latest version of hatch-mypyc allows being installed next the 1.x series of mypy.
I chose mypyc because it has already been out for a little while, and should probably be quite stable by now, but can also try a different version!
Checklist - did ...
What is black formatter?
black is an automatic code formatter for python
you run it on a python file, and it will convert everything to a standard style
see https://black.readthedocs.io for more info
while it's not an official formatter, it became sort of a standard in the community
What about Pycharm auto styling?
Failed to run Black. Whenever I try to run Black from within vscode (ctrl-shift-P > Black: Run Black), I get this error. I can run it from the command line, so I am pretty sure it isn't a Black issue per se, but this is the only plugin where I have problems like this. Hoping some kind person can show me what I am doing wrong. Thanks in advance!
Black currently fails on files containing a carriage return in many positions, while Python itself is happy to treat \r as a newline.
For example:
import black
black.format_str("{\r}", mode=black.Mode())
This is obviously a trivial example, but the problem occurs for a fairly wide range of old Python code from e.g. MacOS, or when files are loaded without universal-newlines (which does still happen occasionally).
As a fix, I d...
what plugin do you have in mind? AFAIK black doesn't offer vscode plugin
With current latest black, 23.3.0 (compiled: yes):
import black
code = """
assert some_long_name, ( # long __________________________ comment
'long ___________________________________ string %s' % str(variable))
"""
black.format_file_contents(code, fast=False, mode=black.FileMode())
Specifically, this stabilizes at the second run:
assert some_long_name, ( # long __________________________ comment
'long _____________________________...
With current latest black, 23.3.0 (compiled: yes):
import black
code = """
if True:
# fmt: off
pass
# fmt: on
pass
"""
black.format_str(code, mode=black.FileMode())
Traceback (most recent call last):
File "repro.py", line 10, in
black.format_str(code, mode=black.FileMode())
File "src/black/__init__.py", line 1084, in format_str
File "src/black/__init__.py", line 1089, in _format_str_once
File "src/black/parsing.py", ...
c99417f Change example from %%writeline to `%%writefi... - deepyaman
f95b43d docs: update note on GitHub .git-blame-ignore-r... - soxofaan
3decbd6 Document each configuration option in more deta... - JelleZijlstra
is the accidential newline convention change in https://github.com/pytest-dev/pytest/pull/11036 something black ought to undo?
I think we're supposed to preserve existing newlines
So if someone changes the whole file, that will be preserved
Thanks for the clarification
When running black (tested with version 23.3.0) as follows:
import black
code = """
if True:
if True:
# fmt: off
pass
"""
black.format_str(code, mode=black.Mode())
This produces the following error:
Traceback (most recent call last):
File "", line 1, in
File "src/black/__init__.py", line 1084, in format_str
File "src/black/__init__.py", line 1089, in _format_str_once
File "src/black/parsing.py", line 94, in lib2to3_parse
File "src/blib2t...
Running black 23.3.0 on the following code:
class S:
if():last_shard.accumulated_answer_json_size_bytes=(#pylint: disable=invalid-name
[0])
Produces the following output:
class S:
if ():
last_shard.accumulated_answer_json_size_bytes = (
[0] # pylint: disable=invalid-name
)
But if we run black on it again we get the following:
class S:
if ():
last_shard.accumulated_answer_json_size_bytes = (
...
Describe the style change
Examples in the current Black style
def f(a, b):
# GOOD
a + b
a **= b
a ** (-b)
(-a) ** b
# NOT GOOD
a**b
a**-b
Desired style
def f(a, b):
# UNCHANGED
a + b
a **= b
a ** (-b)
(-a) ** b
# NOW GOOD
a ** b
a ** -b
Additional context
This seems weirdly inconsistent with literally every other arithmetic operator I'...
AWith current latest black, 23.3.0 (compiled: yes):
import black
code = """
if True:
# fmt: off
pass
# fmt: on
pass
"""
black.format_str(code, mode=black.FileMode())
Traceback (most recent call last):
File "repro.py", line 10, in
black.format_str(code, mode=black.FileMode())
File "src/black/__init__.py", line 1084, in format_str
File "src/black/__init__.py", line 1089, in _format_str_once
File "src/black/parsing.py", ...
That's a known bug that's difficult to fix
I'm running a couple of GHA jobs, one of them being the black formatter inside an Ubuntu container on a self-hosted runner. I've noticed that after running the black formatting action there are files leftover in the _actions directory that aren't owned by the runner's user but rather by root:
ne or more errors occurred. (Access to the path '/home/ubuntu/actions-runner/_work/_actions/psf/black/stable/.black-env/lib/python3.10/site-packages/black-23.3.0.dist-info/INSTALLER' is denie...
!d round
round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
!e
round(1/1024, 6)
@pulsar kayak :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
print(round(1/1024, 6))
@pulsar kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.000977
!d round
round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
This is not #bot-commands, please use that instead.
oops
Is your feature request related to a problem? Please describe.
This is the current behaviour for handling .gitignore:
If --exclude is not set, Black will automatically ignore files and directories in .gitignore file(s), if present.
If you want Black to continue using .gitignore while also configuring the exclusion rules, please use --extend-exclude.
However,...
I personally find this very useful.
Reference: https://click.palletsprojects.com/en/8.1.x/api/#click.Option
Description
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Hi, thanks for Black - it saves me a TON of time, but even more importantly, greatly reduces my mental load when writing code.
Describe the style change
I suggest maybe it a code comment inside a parentheses should remain inside the parentheses.
Examples in the current Black style
Here's the actual use case I am running into today:
# this:
h_mincover_in = (3.5 # ft
* 12)
# becomes:
h_mincover_in = (3.5 * 12) # ft
*...
LGTM thanks, I've always wished one could turn this on all option somewhere ...
Or it was the default, to show defaults ... haha :)
Is your feature request related to a problem? Please describe.
I absolutely never want more than two list items on a single line, regardless of how long that line is. I can manually add a "magic trailing comma" to the final item to get this behavior for a specific case, but that's easy to forget and, when working in a team, not everyone will do this. If this trailing comma is forgotten, shorter lists will end up smooshing it on a single line, which makes for larger diffs that are more ...
@austere lava libcst's native parser is default now? Noice. Congratulations on 1.0.0
Yup! Thanks
@austere lava is the parser recoverable?
No unfortunately
any chance it will or no?
We have a project called errpy that's an error recoverable parser based on tree sitter
It's currently powering pyre and we'll migrate libcst to it too
That will take a while though
Ocaml, eh?
Rust will be the lowest common denominator and there will be python/ocaml/rust apis
I'm asking because there's drama a-brewin' because Python 3.12 changes its tokenizer to raise SyntaxErrors
and it turns out IPython was using the ability for the tokenizer to gulp invalid code to support some of their magic
Aha
and now they are upset as they would have to migrate to something and there doesn't seem to be anything to migrate to
so you could come in on a white horse and save that shit
Do you have a link to the drama?
Sidenote: it's very hard to make a peg parser error recoverable while also keeping it usable
Ouch, it seem there was some changes in python 3.12 tokenizer that breaks many of IPython functionality. A stricter tokenizer that raise SyntaxError early make it hard/impossible to do some of the transform we are doing. like detecting incomplete code to add new lines 1/n
Oh of course the blue bird of toxicity
Mastodon isn't better. Like soylent green, it's people!
I find that CPython's implementation of these things have conflicting goals with dev tools (performance vs UX)
replied on the thread, let's see what they say
by the way
Black will be now met with new grammar shenanigans
f"hey {"zsol"}!"
this will be fun for Batuhan to work around, eh? if even possible
yes, I already implemented and merged support for PEP 695 in blib2to3, but I'm not touching this f-string stuff
Understandable
Is this related to a problem? Please describe.
The documentation suggests using flake8-bugbear instead of just bumping max-line-length to 88, as bugbear already handles a line max 10% longer than max-line-length. However, the example with bugbear below it still uses 88.
What this effectively means is that flake8 (with bugbear) won't complain about lines up to 96 characters long.
...
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Describe the bug
When running black with --stdin-filename, the pyproject.toml configuration isn't respected if running black from a parent directory relative to the location of pyproject.toml.
To Reproduce
Suppose you have a directory structure as follows:
backends
├── pyproject.toml
└── src
└── app
└── main.py
where main.py has just one print statement such as print("This line is too long") and pyproject.toml has this `b...
black fails for me when run via precommit in pypy3.8 ci
Traceback: https://paste.pythondiscord.com/kibejapasa
Description
Fixes https://github.com/psf/black/issues/3718
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
This code is a little odd, but before it left it as is and now with 23.3.0, the output is changed
def changes(a, b, c="C", **kwargs):
z, y = kwargs["a"], kwargs["b"]
x, w, v, = (
"X",
"W",
"V",
)
def stays(a, b, c="C", **kwargs):
z, y = kwargs["a"], kwargs["b"]
x, w, v = (
"X",
"W",
"V",
)
With 22.x, these would both be left as is, but with 23.3.0, the changes function is changed to a tupl...
Is your feature request related to a problem? Please describe.
The documentation here: https://black.readthedocs.io/en/stable/usage_and_configuration/black_as_a_server.html#usage
States: There is no official blackd client tool (yet!).
Describe the solution you'd like
Well, I wrote one for me personally, and I thought it'd be nice to give it to someone who knew how to add it to the codebase, but I'm not super dedicated, I just figured, it's probably copy/pastable into th...
Is your feature request related to a problem? Please describe.
I am unsure how to cite Black in my research articles.
It would be useful to have an explicit metadata component describing how to cite Black.
Describe the solution you'd like
A CITATION.cff file could be added to the root of the repository. This would allow GitHub to automatically generate a citation in both APA and BibTeX format. Additionally, reference manager plugins such as Zotero will be able to automatic...
Description
This pull request adds a CITATION.cff file to the root of the repository. This resolves #3722 and follows GitHub's recommendation.
It will achieve several things:
- Provide explicit information (metadata) on how to cite Black
- Allow GitHub to automatically generate APA and BibTeX formatted citations
- All...
ABS_PATH_HERE = "/home/users/Documents/dev/project-amogus/helpers/sus/carrots/python/code/"
this line does not get formatted and split into multiple lines.
this one. black.
Enterprise malware scans flag black.exe and blackd.exe due to neither binary being signed. This can be checked/verified via AuthenticodeSignature baked into Windows:
AuthenticodeSignature -FilePath black.exe
Directory: ${super long directory}
SignerCertificate Status Path
----------------- ------ ----
No...
formatters should make your code easier to read. black is a little shy about preserving the AST... i find "rm" does a really good job of making my code more readable
Describe the style change
Examples in the current Black style
match status:
case ThisIsAnExampleStringEnum.this_is_example_status_one | ThisIsAnExampleStringEnum.this_is_example_status_two | ThisIsAnExampleStringEnum.this_is_example_status_three:
print("ok")
case _:
print("not ok")
Desired style
match status:
case (
ThisIsAnExampleStringEnum.this_is_example_status_one
| ThisIsAn...
In this PyCon talk, Lukasz said that black uses asyncio to parallelize formatting: https://youtu.be/oVhJAVS3g00 . But the talk is mostly about ProcessPoolExecutor and shared memory. I didn't think asyncio would help with compute-intensive work.
You've heard it many times: the GIL is a problem for using all your CPU cores in one program. Among the generally accepted solutions there's multiprocessing, a way to orchestrate a group of worker processes to spread CPU load over many cores. This solves the problem for many use cases but if you have a lot of data to pass around there and back a...
it doesn't; it's purely used to orchestrate things: https://github.com/psf/black/blob/b60b85b234d6a575f636d0a125478115f993c90c/src/black/concurrency.py#L119 is literally the only async function in black proper
src/black/concurrency.py line 119
async def schedule_formatting(```
the ProcessPoolExecutor is started a couple lines above that
thanks. that's similar to what Łukasz showed in the talk.
frankly I don't understand why we use asyncio.
Is it used as a better abstraction over using multiprocessing directly?
<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:
- Update Black's version if a newer release exists:
pip install -U black - Use the online formatter at , which will use
the latest main branch. - Or run Black on your machine:
- create a new virtualenv (make sure it's the same Python version);
- clone this repository;
- run
pip install -e .[d]; - run `...
Description
Avoids a Python 3.12 deprecation warning.
Subtle difference: previously, timestamps in diff filenames had the +0000 separated from the timestamp by space. With this, the space is there no more.
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
whats this??
black is an automatic code formatter for python code
check out the link in the channel description for more info
Description
Fixes #3716
The current phrasing of the Flake8 section of the line length documentation is very open.
This PR makes it more concise and explicit, as well as change the max-line-length example when using flake8-bugbear to 80, as explained in #3716.
Checklist - did you ...
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add / update tests if necessary?
- [X] Add new / update outdated documentation?
c76e0b0 Bump pypa/cibuildwheel from 2.13.0 to 2.13.1 (#... - dependabot[bot]
688f78d Bump peter-evans/create-or-update-comment from ... - dependabot[bot]
The upload_binary workflow depends on actions/upload-release-asset.
The action hasn't been updated in over 2 years, and runs using Node12. Since GitHub is removing Node12 from their runners, soon enough the workflow won't work at all.
https:...
Black fails with incorrect encoding. See the following example:
# coding: mypy
def f(x: int) -> int:
return x + 1
The expected behavior:
no error.
The actual output on black
error: cannot format /home/xxm/Desktop/example.py: unknown encoding: mypy
Oh no! 💥 💔 💥
1 file failed to reformat.
How to reproduce it:
- store the above code in a single python file "example.py"
- run with the command "black example.py"
...
Does mypy have its own codec?
no
I have an import (which is already formatted in a way that doesn't violate max-line-length)
from base.tests.blabla.v1.something.even_more_deep \
.this_is_one_file.this_is_also_something.one_file import Ship
after running black with the command
black -l 99 --preview ./
the import would be formatted as
from base.tests.blabla.v1.something.even_more_deep.this_is_one_file.this_is_also_something.one_file import (
Ship,
)
which would violate the --max-...
because it would change the AST
i.e. how the code behaves
there are other tools that can reorder imports already
ruff
I would have said the same, yeah
Hi guys, girls, people
This is presumably a really common request so hoping someones written someway around it
As a developer I want to be able to postpone triggering the file watcher if there is another change in certain short period of time ("quiet period") - i.e. a developer touches one line in the scope of watched files, saves the file and a second later she makes another change, thus triggering another run.
What steps will reproduce the problem?
Enable file watchers.
Make a change in your files, triggering the file watchers to start the build
Realize you wanted to make another tiny change in some other file.
Waiting for the previous build to finish takes lot of time
What is the expected result?
When the developer makes the first change a sort of "quiet period" starts (e.g. 10 seconds) at the moment waiting out any other potential change in watched files the developer might still want to make. If she does not make another change during the quiet period, file watchers start the build. Any change during this quiet period prolongs the quiet period (resets the timer).
Ideally the length of the quiet period would be configurable.
What happens instead?
currently there is not an option to set the quiet period
Also not only does it avoid waiting, but sometimes im halfway through writing a line and it reformats and moves my cursor which is infuritating
really good tool though
this sounds like a bug with some IDE, not black itself?
Description
Fix #3638
Checklist - did you ...
- [x] Add an entry in
CHANGES.mdif necessary? - [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Hi all, I have a question. I write some Python code in markdown document.
Just like this:
class Solution:
def pivotInteger(self, n: int) -> int:
for x in range(1,1000):
if (1 + x)* x= (x + n) * (n - x + 1):
return x
return -1
How can I automatic format the code with black?
I'd probably use https://black.vercel.app/ to copy-paste the snippets back and forth.
Playground for Black, the uncompromising Python code formatter.
Thanks for your sharing. I think it would be better to format the python code in markdown document automatically.
https://github.com/doocs/leetcode/blob/main/run_format.py#L62-L84 Here is my current solution. And I am looking for a better way 🙂
you could try something like https://github.com/hukkin/mdformat-black
you could also use black.format_str(...), see https://github.com/psf/black/issues/779
https://github.com/adamchainz/blacken-docs will also format Python code blocks in markdown files
Oh nice!
That's great! Thank you all, guys.
Hello folks. I am curious that if there are some issues when I use Black with pre-commit to configure options via pyproject.toml file.
I use Python 3.11, pre-commit 3.3.1, and Black 23.3.0. I run the below codes and command on MacOS Ventura 13.4.
I install packages in .venv directory created by poetry.toml file.
The below one is my pyproject.toml file.
[tool.black]
line-length = 120
target-version = ["py311"]
The below one is my .pre-commit-config.yaml file.
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
I run pre-commit command with poetry because I manage my packages with it. Thus, I create a command to run lint with Makefile file like the one below.
.PHONY: lint
lint:
poetry run pre-commit install && poetry run pre-commit run
The pyrpoject.toml , .pre-commit-config.yaml , and Makefile exist in the same depth of directory. It looks like the one below.
├── .venv
├── Makefile
├── poetry.lock
├── poetry.toml
├── pyproject.toml
├── .pre-commit-config.yaml
└── src
When I run make lint command, Black fixes line length even it is not over 120. Can I get any help?
Is this related to a problem? Please describe.
The issue template on GitHub url link in documentation seem not valid: it is currently pointing to this link, but this is just an empty new issue and have no template to choose from.
Describe the solution you'd like
I think it should be point to here instead (which have ...
Describe the bug
Black crashes when run on some code that includes a multiline statement with #type: ignore comments on multiple lines.
To Reproduce
For example, take this code:
class Foo:
def foo(self) -> None:
if True:
self.foooooo= ( # type:ignore[error-code]
Baaaaaaar( # type:ignore[error-code]
self.baz()
)
)
And run it with these arguments:
$ black file.py
The resu...
Description
Fixing #3736
Modified the issue template on GitHub url link in documentation to the url here that actually have the issue template options.
Checklist - did you ...
- [x ] Add an entry in
CHANGES.mdif necessary? - Not necessary - [x] Add / update tests if necessary? - Not necessary
- [ x] Add new / update outdated documentation...
slick move right there with the zero. I too believe zero should always be put on a new line. It's too special not to be.. 🤦♀️
you can always increase or decrease line length setting
that wouldn't really help much tho. The default length is ok, mostly. But it'd be better if there was some checking of the length of elements. As far as I remember, a list gets expanded if it doesn't fit within the max line length, but.. cmon, 1 element with a total of 3 extra characters? Couldn't it like, check the amount of elements in the lists, and not do that if you're barely over the limit and resulting in 2 extra lines with 1-2 characters only? That doesn't seem like a difficult "fix", and would look a lot better in.. pretty much any case I can think of. Basically, to have a range as the limit, with a strict and soft limit, not just a strict limit..
And even if for some reason doing that is impossible.. why couldn't it just do this instead.. looks a lot better 💀
you can do that yourself if you add a trailing comma right?
I'm pretty sure blackie chooses for u, whether u have a trailing comma or not, and that depends on the length, and no, I don't believe you can do what I'm asking for. At least I don't know how to
this immediately gets formatted to the above version
can you paste the code?
best to @ me, chances are I won't see the message otherwise:
test_data["Fare"].fillna(
train_data.groupby(["Pclass", "Embarked", "Parch", "SibSp"]).Fare.mean()[3]["S"][0][
0
],
inplace=True,
)
lol ok yeah doesnt matter
Description
Fix #3737
Analysis of this issue:
Black has no problem parsing multiline consecutive magical comments like type: ignore, it works fine with these examples:
print( "111") # type:ignore
print( "111" ) # type:ignore
print( "111" ) # type:ignore
But Black encountered issue when parsing multiline open-parenthesis consecutive magical comments, code like this will cause Black to produce an `INTERNAL ERROR: ...
Describe the bug
black formats the following code improperly handling # Trailing same-block.
x = 1
# Leading comment
del (
# First inner own-line
x # Trailing comment same-line
# Trailing comment own-line last inner
) # Trailing same-block
# Trailing own-line
Result
@@ -4,5 +4,6 @@ del (
# First inner own-line
x # Trailing comment same-line
# Trailing comment own-line last inner
-) # Trailing same-block
-# T...
hmm
so yesterday i switched pre-commit at work over to using mypyc black because i wanted things to be faster https://github.com/psf/black/issues/3405#issuecomment-1600079594
today i discover that now black is hanging very often
py-spy tells me:
__enter__ (multiprocessing/synchronize.py:95)
get (multiprocessing/queues.py:102)
_process_worker (concurrent/futures/process.py:237)
run (multiprocessing/process.py:108)
_bootstrap (multiprocessing/process.py:315)
_launch (multiprocessing/popen_fork.py:71)
__init__ (multiprocessing/popen_fork.py:19)
_Popen (multiprocessing/context.py:277)
start (multiprocessing/process.py:121)
_adjust_process_count (concurrent/futures/process.py:675)
submit (concurrent/futures/process.py:697)
run_in_executor (asyncio/base_events.py:814)
<dictcomp> (black/concurrency.py:163)
schedule_formatting (black/concurrency.py:161)
_run (asyncio/events.py:80)
_run_once (asyncio/base_events.py:1890)
run_forever (asyncio/base_events.py:596)
run_until_complete (asyncio/base_events.py:629)
reformat_many (black/concurrency.py:108)
new_func (click/decorators.py:26)
invoke (click/core.py:760)
invoke (click/core.py:1404)
main (click/core.py:1055)
__call__ (click/core.py:1130)
<module> (black:8)
hmm but there are way more processes than i expect, another classic multiprocessing.cpucount() thing?
oh this sounds quite a bit like https://github.com/psf/black/issues/2513
okay i'll patch that in and see if it helps. weird that it's only happening with mypyc...
oh but maybe the actual difference is some ci caching changes that work made
anyway, could be nice for --workers to be specifiable by env var as well. is that a patch you'd be willing to take?
kind of wary of that as we end up with three different ways of configuring Black (command line, config file, env vars), and it will be confusing to reason about how they interact. Seems like we already accept BLACK_CACHE_DIR though
why should --workers be special and deserve an env var?
it's not critical by any means, but feels weird to change our incantations to specify --workers=fixed_number when the fixed number only matters in CI. the assumption that local machines and CI have same number of cores doesn't really hold
ok that makes sense, you'd want to use the same pre-commit invocation both locally and in CI, but you reasonably want a different value for --workers in both cases
an env var is a good fit in that case
Is your feature request related to a problem? Please describe.
Describe the solution you'd like
Describe alternatives you've considered
Additional context
Fixes #3742
- [ ] Add an entry in
CHANGES.mdif necessary? - [ ] Add new / update outdated documentation?
Describe the bug
We started to use black and used it to reformat the whole repository. One week later, on the same black version, many lines have been changed back to what they were previously.
Merge request 1, introducing black:
Merge request 2, one week later:
I don't mind which vers...
Looks good, but this should also be mentioned in the documentation, maybe somewhere in https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html (which I think is rather different on main, I need to do a release sometime).
Fixes #1239.
I believe we can fix this without going through the preview style as we're only changing code that was not yet formatted with black; https://black.readthedocs.io/en/stable/the_black_code_style/index.html#stability-policy explicitly calls out that we can fix bugs where we remove comments.
453828d Fix not honouring pyproject.toml when using std... - renan-r-santos
https://peps.python.org/pep-0701/, which will be in Python 3.12, adds support for several f-string variations that our current parser won't handle:
>>> f"{f"{"f"}"}"
'f'
We should support this new syntax, somehow.
I don't know if this is doable with blib2to3.
Describe the bug
Long strings and f-strings are not being formatted to line-width.
New strings created by black are not respecting line-width.
To Reproduce
For example, take this code for variable a:
a = f"{nested_ui_dict_val[i][j][k]['name']} ansible_host={nested_ui_dict_val[i][j][k]['mgmt_ip']} MYPORT=111222333 PATH={nested_ui_dict_val[i][j][k]['path']} ip={nested_ui_dict_val[i][j][k]['ip']} NODESTUFF={nested_ui_dict_val[i][j][k]['nodestuff']} MOREID={neste...
Intresting
IPython is a very expensive import, like, at least 300ms. I'd also venture that it's much more common than tokenize-rt, which is like 30ms. I work in a repo where I use black, have IPython installed and there happen to be a couple notebooks (that we don't want formatted). I know I can force exclude ipynb, but this change doesn't really have a cost.
Currently the verbose logging for "Sources to be formatted" is a little suspect in that it is a completely different code path from get_sources.
This can result in bugs like https://github.com/psf/black/pull/3216#issuecomment-1213557359 and generally limits the value of these logs.
This does change the "when" of this log, but the colours help separate it from the even more verbose logs.
7be2735 Allow specifying --workers via environment va... - hauntsaninja
black . is changing things in gallery and scripts for me
93989e9 Integrate verbose logging with get_sources (#3749) - hauntsaninja
This speeds up black by about 40% when the cache is full
Does black have a special case for # type: ignore comments? After switching to pyright and # pyright: ignore comments people noticed that black is much more liberal with re-shuffling the comments which leads to frustrating cycle of fighting with it to keep the comments on the lines they intended to be on. Curious why we didn't notice it before.
yes. there's an open issue about extending the special treatment to pyright comments
where can I upvote?
I think I found it https://github.com/psf/black/issues/3399
Actually this seems different...
I guess there's just a PR https://github.com/psf/black/pull/3661
Describe the style change
In functions with the new type parameter syntax, the type parameter bracket should only be made multi-line if it itself does not fit on one line. (Sorry, this is best explained with an example; see below.)
Examples in the current Black style
def f[
T
](a_long_param_name: list[T] | tuple[T, ...], another_long_param_name: T) -> list[T]:
pass
def g[
T
](
a_long_param_name: list[T] | tuple[T, ...]...
Hi.
A question about how black uses pyproject.toml. We have a big repo with some nested pyproject.toml's. In this case black will pick the closest pyproject.toml file based on current directory while we would preferably like to specifiy our black config only in the root pyproject.toml file.
In contrast, ruff does exactly this and it works pretty weel for us https://github.com/astral-sh/ruff/blob/main/crates/ruff/src/settings/pyproject.rs#L48 It will check that there is actually a tools.ruff section before deciding to use a pyproject.toml file.
If this is something that seems reasonable I am willing to create a PR for it
Description
- Added the command for activating the virtual environment in Windows:
.venv\Scripts\activate - Included an additional test
tox -e run_selfto the pre pull request procedure, as it is also part of the Lint GitHub Action. (lint.yml) - Corrected a typo in the pip command:
pip install [-e] .[d]changed topip install -e .[d]
Checklist - did you ...
- [x] Add an entry in `CHANGES.md...
this is something i've wanted too, if no one else chimes in definitely make an issue / PR for it!
makes sense to me!
anyone aware of a pseudo-repr function thats able to render strings or tuples in a black safe manner - i'd like the setuptools_scm python version file template to yield black safe code, without having to sort out details like line length or quoting myself - my impression is that the alternative would need to have black format it and i'd like ot avoid that
Wdym by "black safe"?
String that is already formatted in black-like style (so applying black to it does nothing)?
Describe the bug
Given the following configuration in pyproject.toml
[tool.black]
line-length = 120
extend-exclude = [
'^(?:([^\/]+\/)+(?:test_.*\.py|.*_test\.py))$',
'.github',
'.mypy_cache',
'.pytest_cache',
'venv'
]
Black fails with the error:
Error: Invalid value for '--extend-exclude': Not a valid regular expression: unbalanced parenthesis at position 17
But this is a valid regex that supposed to match any files starting ...
Description
Updated the Black classes and the Black exceptions page in the Developer reference. It is now matched with the current code base.
- All Classes under
src/blackare now documented - All exceptions are now documented
- Modified a few docstrings in
src/black/handle_ipynb_magics.pyandsrc/black/trans.pyto conform to the rst syntax (enforced by Sphinx).- The docstrings we...
before
[
(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
),
]
after
["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]
Description
This PR replaced the deprecating set-output command used in the diff_shades_comment GitHub Action with latest GitHub supported method.
See this GitHub blog about this deprecation.
The original method of setting variables directly using the set-output command has now been replaced with setting variables through the GITHUB_OUTPUT environment variable.
A...
Hello,
I seem to have found a bug in black's preview style regarding assignment expressions, that has been present since version 23.1.0.
Describe the bug
When using an assignment expression in my code example, black with preview=true complains it cannot parse the line. Black preview=false accepts the code happily and leaves no changes.
To Reproduce
Here's my code example:
# file.py
from pydriller import Commit
commits: list[Commit] = []
update_hashes...
:incoming_envelope: :ok_hand: applied timeout to @pliant fossil until <t:1688324939:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Description
Relates to #3708 by deleting the .black.env folder specified by ENV_PATH on action completion.
I had a difficult time replicating the issue above @JelleZijlstra and I can't see that any changes were made to stable that would effect this behaviour. Probably worth deleting that .black.env dir anyway?
Checklist - did you ...
- [X] Add an entry in
CHANGES.mdif necessary? - [X] Add / update tests if necessary?
- [X] Add new / update outdated d...
Describe the bug
ERROR: Could not find a version that satisfies the requirement hatchling>=1.8.0 (from versions: none)
To Reproduce
on black installation
For example, take this code:
this = "code"
And run it with these arguments:
$ black file.py --target-version py39
The resulting error is:
cannot format file.py: INTERNAL ERROR: ...
Expected behavior
Environment
- Black's version:
- OS and Python...
Fixes https://github.com/psf/black/issues/3658, and ensures that https://github.com/psf/black/issues/3658 won't regress later.
Pushing this now to see what CI thinks...