#black-formatter
1 messages Β· Page 35 of 1
I never feel like the project is well-oiled as a maintainer lol :p
There are so many infra and process improvements possible!
ππΏ I'll try to have a look on friday if it's still TODO, unfortunately no time before that
Yeah! I gott'a get a feel for how all'y'all do your thing and work from there. I'll try to read through the code a bit more or something. I'll look for somethin' light in the issues list to hit at.
CI is complicated to write, ah. Also pretty annoying to test lol
Hmm is there any benefit to restricting permissions to only contents: read in the workflows themselves if in the repository actions settings the default permissions are exactly that?
because they are indeed set to contents: read only by default
Function format_cell() hasn't been documented yet.
It could be helpful for users to have it documented.
that's done when it doesn't fit the line length limit
so if this is inside deeply indented code then that would happen
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
lol
yep :D
π even i need to add myself to authors
it does also say "Multiple contributions by:" so even if their PR was merged, that's still not multiple!
who are you to be the judge of what's a contribution! /s
π π
that you? :D
oh nevermind then π
<!--
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 `...
another episode in "Black gets blamed for things it didn't do" π
Is there any desire for Black to be compatible with the VSCode Dev Containers extension?
The tl;dr is that it makes a nice little docker env that lets VSCode devs work inside of that while dev-ing. I haven't seen it in too many Python packages besides Pandas (https://github.com/pandas-dev/pandas/blob/main/.devcontainer.json) but there's a number of smaller CLI-type packages I've used that have it.
The only con I can think of is that it's an additional file in the root, which, admittedly, is kind'a gross.
(Secretly, I'm just trying to figure out something to mess with, and my day job is a lot of ops-type stuff. Not a biggie if y'all aren't into it.)
I'm a little confused, is this file meant to preconfigure an GitHub Codespaces environment? ... because I'm not even sure if the psf organisation has access.
Or is this also applicable to local development in VSCode?
Ah it's the latter reading through the docs
Ah, apologies for not bein' more specific: yeah, it's the latter thing. Local dev in VSCode. I don't think I've ever done Codespaces stuff, so I don't know much about that.
When one places quoted text within brackets that spans multiple lines, it might be useful to not format it into one long line, as shown below:
Black v22.3.0
Options
--line-length=88
--safe
...
Description
This is just a tiny optimization to skip unnecessary calls to get_future_imports.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
is there documentation on all of the possible config options?
aside from black --help I can't seem to find anything
Description
Here's a doc update for #2926, #2990, #2991 and #3035. Conveniently, they are similarly themed, so I wrote quite a terse doc, and made another section shorter too. Feel free to elaborate if you see the need, I'll have to catch a train now π
Checklist - did you ...
- [x] N/A Add a CHANGELOG entry if necessary?
- [x] N/A Add / update tests if necessary?
- [x] Add new / update outdated documentation?
You can change line length limit to your liking.
You can't change how it splits once you go over it
# fmt: off
nasty code
# fmt: on
is there an issue for black magic comma in context managers? I couldn't see one with a search https://github.com/psf/black/issues?q=magic+comma+context+manager
is it ever correct for black to emit ,) when not in a tuple?
normalization is what Black does. Before you run Black code is not normalized, afterwards it is
--skip-string-normalization skips the things Black does to strings (change quote style and mess with the prefix)
s = 'single quotes will not be changed to double quotes'
s = u"this redundent u prefix also won't be removed"
oh and also the prefix won't be reordered (can't remember what the current order is though)
oof yeah that is definitely a bug
context managers in general could do with a style overhaul since it sucks right now
Yeah, but I am not sure if black handles those parenthesized ctxmgrs well either
I'm sure I raised an issue about this somewhere
I wish black.now.sh had a bug report button
omg my wish has been granted
yup
Thanks for tackling this! I think you may have gone overboard with the terseness though :)
Hello i would like to share my project feel free to download it, but please credit
this isn't a channel for sharing your projects
i did not know
It doesn't flow very nicely, but I can't think of a way to improve it so it's fine. I'd appreciate a re-review from Jelle though.
Are there any (hopefully low effort) PRs people want to see merged before a release? If not I'll just get Felix's PR in and start the release checklist for v22.6
I looked at the changelog and I don't think there's anything that was left half-finished user-facing wise so I think there's nothing truly blocking the release. Just a matter of me clicking buttons :)
This release is rather light especially given it's been three months, but that's just the byproduct of my lack of activity on the project. I should have more free time now though so that'll change :)
oh hi @errant barn FYI I am editing your PR locally, I'll push my changes soon. You can lemme know if they look good!
got a flow idea? nice
yeah, turns out sleep helps :)
often :D
Pushed, please take a look :)
I wonder if this will work as a hacky preview :p
dammit, you weren't supposed to yoink the code within the file and preview it discord.
ah all of the CSS is broken, that's unfortunate
oh, apparently saving a whole webpage also downloads a whole folder with the JS and CSS assets... that's annoying. I would've thought Chrome would put everything in a single archive
Nice, that looks good
Kk thank you! Not sure if I should wait for Jelle's review?
I think we're fine, but if you'd like!
lol, Rich is always going to be my unofficial nickname, everyone thinks of it :p
progress! (the release CI item is deferred for the release after this one)
if anyone wants to help this user, please do, currently busy with release prep. https://github.com/psf/black/issues/1985#issuecomment-1167837098
Description
I kinda forgot how to do a release :slightly_smiling_face:, good thing we have release docs!
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> this is literally news itself :D
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Not really sure who is active right now so I just guessed for my review requests :p
I'mma go for a walk/run now. When I come back (in ~3 hours) I'll cut the release.
look look I contribute
LGTM - Couldn't find a typo or anything.
I'm a little nervous the mypyc wheels might fail to build, but the diff-shades workflow does mean the linux wheels should build without issue so that makes me hopeful.
http://mirror.es.its.nyu.edu/epel/7/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://mirror.es.its.nyu.edu/epel/7/x86_64/repodata/repomd.xml: (28, 'Connection timed out after 30001 milliseconds')
Trying other mirror.
grrrr, now I am properly nervous
eh, seems to building fine, just a hiccup at the start
> black --version
black, 22.6.0 (compiled: no)
Python (CPython) 3.10.5
Is this intentional? I couldn't find any information regarding dropping of mypyc compiled wheel support.
.<
whatβs black formatter?
An autoformatter for Python code
oh cool
!remind 30M check in on the 3rd rerun of the mypyc wheel build workflow, sigh
Your reminder will arrive on <t:1656383890:F>!
Here's your reminder: check in on the 3rd rerun of the mypyc wheel build workflow, sigh
[Jump back to when you created the reminder](#black-formatter message)
Irrelevant, Jelle helped me sort out my zip troubles.
def f():
"lorem ipsum ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd sus"
> black --version
black, 22.6.0 (compiled: yes)
Python (CPython) 3.10.5
> black test.py
error: cannot format ...
I have preview enabled.
Description
Deletes an extra coma in CHANGES.md
<!--
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 `...
Is your feature request related to a problem? Please describe.
When formatting a file whose syntax requires a higher version of Python than the one Black is running on, Black fails (with a cannot use --safe with this file error). This is made more confusing because Black only fails when changes are made. If no changes are made, then everything seems to be OK and I won't ever know that the environment is faulty.
Describe the solution you'd like
It's still unclear whether t...
We should make up our minds on psf/black#751
If we want to support reading python-requires in pyproject.toml then making --target-version the minimum is only option that makes sense. And I'd like to support reading python-requires so I vote for that.
we should make it the minimum
@neon loom I think you misunderstood psf/black#3124, it's asking that Black should read [project.python-requires] to automatically set --target-version AFAICT (based off the comment they linked)
Ya, it did. I also want to use hatch + pyproject.toml as much as we can - If it's out of place feel free to delete
Good chance my quick 20 PR / Issue read caused me to misunderstand
anyone ever seen this error?
error: cannot format docs/conf.py: Can't pickle <enum 'COLOR_DIFF'>: attribute lookup COLOR_DIFF on black failed
...
Oh no! π₯ π π₯
10 files failed to reformat.```
this is black 22.6.0 and python 3.10.4 if it helps
i cant seem to get a more verbose traceback even with --verbose
weird, is your environment clean?
could happen if you manually changed enum.py or something
!remind 18H test out setuptools' experimental PEP 660 support
Your reminder will arrive on <t:1656619858:F>!
Black seems to be handling comments in a way that i don't quite want. So i got this:
# @app.route("/shutdown", methods=["POST"])
# def shutdown():
# shutdown_server()
# return "Server shutting down..."
After formatting, i get:
# @app.route("/shutdown", methods=["POST"])
# def shutdown():
# shutdown_server()
# return "Server shutting down..."
I get why that happens but I don't want it to do that. I could be tripping but this didn't work like this in previous versions. I checked configurations and there doesn't seem to be a way to change it.
We don't really consider comments to have any special status wrt formatting, although it is annoying that commented code will break
As a workaround you could use # fmt: off/on or encapsulate the code in a multiline string
You would perhaps agree that
# any old comments
# unaligned
# should be put back
huh? i'm not sure i understand
To preserve commented out code like you presented would be bad, is what I'm trying to say. It's probably hard to determine that a comment contains code (and it is intended as such), and we don't want to take previous formatting into account in any of our formatting.
IIRC this probably wasn't changed in the latests release π€
@pallid dove So if you were just after "disabling" it, this is probably it 
i suppose that'll work. thanks!
no idea why but my discord is being weird and i can't see any new messages except for when going into the search bar
I must religiously share the teachings of Uncle Bob, though :D "don't check in commented code" https://youtu.be/2a_ytyt9sf8?t=2263
Interesting. I guess he does make a good point.
Seems like most of this report is prefilled, hopefully it has all the necessary details. I was trying to use the playground to check things, and it seems like it's just erroring out. I changed out my actual code to something very simple and the issue seems to persist.
Black v22.6.0
[Playground link](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AB7AFddAD2IimZxl1N_Wlws4TBexXdmg613D2W2vO1gykBlg0ElxjidjH2deuosqH32nmM8xj1PdbPxzNWkHiZyYJ80c_DpGmoskeYwGs6...
damnn felix u are fast
;)
Is this related to a problem? Please describe.
BlackConnect plugin since 0.5.0 has an ability of running the blackd on plugin initialization, you only have to specify blackd executable path in plugin config.
This plugin is open-sourced and is reliable, has rich configuration, and supports various configurations.
Describe the solution you'd like
I suggest rep...
Is this related to a problem? Please describe.
Wrong version on https://black.readthedocs.io/en/stable/
Describe the solution you'd like
Publish docs for 22.6.0
Here's your reminder: test out setuptools' experimental PEP 660 support
[Jump back to when you created the reminder](#black-formatter message)
Description
Fix the handling of # fmt: skip when it's at a colon line.
When the Leaf node with # fmt: skip is a NEWLINE inside a suite Node, the nodes to ignore should be from the siblings of the parent suite Node.
There is a also a special case for the ASYNC token, where it expands to the grandparent Node where the ASYNC token is.
This fixes #2646, #3126, #2680, #2421, #2339, #2138.
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
-...
man, do I hate past me's decisions how to structure the documentation
it's really awful
I think the fact psf/black is the first major project I've ever managed or maintained (my personal ones don't count) shows 
learning on the job is totally fine, but it's unfortunate that some mistakes are hard to undo, gah
do you guys even need stable branch anymore?
since now Black is no longer beta
and it should be picked up properly
I think some integrations reference it
π
I know our old pre-commit sample configuration did (which was a very very very bad idea)
we're kinda stuck with it Β―_(γ)_/Β―
it's a tag right now btw, which I dislike
yeah, branch is more flexible
you have to force push tags, right
I mean, you probably delete it and readd
nah git tag -f stable 22.6.0 is enough
mhmm, and pulling an updated tag is really annoying since git assumes they won't change
I think you have to delete your local tag before being able to pull an updated tag from a remote
according to some folks in the core team, it's safer cause it's harder to accidentally change it (you need to pass --force)
I disagree that's important enough
branch protection with deployment requirement perhaps?
yup
but I think there's some pushback on that front too since it's added complexity for not much gain
yeah, maybe I'll suggest it, but I don't like suggesting ideas that might get shot down (this is a personal thing, nothing to do with the core team or any of its members)
the whole stable branch thing is an added complexity, time to drop in (20)23? :P
and break a whole wack of old pre-commit configurations 
are you not on the core team of psf/black?
I am part of the core team, but I don't feel like I have much authority when it comes to policy.
ah
whether it's tag or branch, I don't see why it shouldn't be automated
I assume it hasn't be done because someone would have to actually do it since that's the standard problem of OSS
or I guess development in general
nah, it's hard to automate it right now since the policy is to only update it once we're confident the release isn't broken
having to trigger a separate workflow would still be less work than doing it manually
and it standardizes the process
yeah I suppose, and if we can't fix the weird issue with RTD picking up the old commit of an updated tag, we could just fire a rebuild request in the workflow :p
guess this needs a reproducer
https://readthedocs.org/projects/black/builds/17325177/ .. check the commit built here
and this is the rebuild I forced https://readthedocs.org/projects/black/builds/17325383/
yeah, I'm just thinking of making a separate project where we can freely test that out without playing with an important repo lol
maybe I'm volunteering
just, tomorrow...
I mean if you don't get to it, I'll get to it eventually
although I have an insanely long to-do list so that might as well be effectively never 
Description
See the deprecation notice:
https://docs.readthedocs.io/en/stable/config-file/v2.html#python-version
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- CHANGELOG entry seems unnecessary as it's not user-facing
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
I see you guys don't have PR builder enabled on RTD
I think the last time I tried enabling that it didn't work since I don't have admin permissions to the GH repo Β―_(γ)_/Β―
you have RTD access?
yup, I tried enabling PR preview in the RTD admin panel
I suppose if the webhooks are outdated it might require admin perms on GH repo
which... is possible since this project has existed for a while
I have admin access if you need anything
There's a switch for PR builder here:
https://readthedocs.org/dashboard/black/advanced/
Which in itself shouldn't require admin access on GH I think but it's possible you run into one of these issues in which case that access would be needed:
https://docs.readthedocs.io/en/stable/pull-requests.html#troubleshooting
I can try again right now and see what error it gives me
half of it works at least
it might require a reconnect
which the UI seems to make it seems as if it's more disruptive than it actually is (I think, I know I did that once but I can't recall if that's the actual place lmao)
well I made my RTD account using my GH account so I'll probably have to set up a password first
lolwat
you click disconnect, it disconnects and then you can connect again
I have no clue what would happen if you were to log out
*phones support*
oh they fixed it
you can longer shoot yourself in the foot π
I guess my account does have password set up then
I didn't know

holy, I even have it saved in password manager, when did I do that...
haha :p
Description
Fixes #3146
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
The way that vim automatically indents python code[^1] differs from the black format. I'm aware of two differences: (i) lines within parentheses/braces are indented twice rather than once and (ii) closing parentheses/braces are not dedented. These differences can be seen clearly by looking at a function argument list that spans multiple lines. Here is such a list as it is automatically formatted by vim (i.e. typed without hitting tab or backspace):
# $ vim -u /etc/vimrc +'filetype in...
Seems good to me, but would love to have some other IntelliJ Developers confirms this works / +1 this please. I don't use it so feel bad merging without a few IntelliJ users agreeing this is right and the way to go.
@mint barn hey, can you clarify whether you want me to take over the PR psf/black#2916 for ya? the way you worded your reply is a bit unclear, and while it sounds you are going to come back to the PR, you haven't pushed any updates (to resolve the outstanding review comments)
yeah u can take over, the second part meant that when u are iterating over my code, if something is unclear let me know
Sounds good, thanks for clarifying!
I think I managed to fix mypyc/mypyc#917 π
The root issue is that mypyc didn't know builtins.set was a built-in name, so it guessed it came from the module globals. This didn't blow up anything up somehow... until the dataclasses commit which made the __annotations__ logic for dataclasses try to better preserve the type annotations (previously they would be erased to type)
Description
The Actions Status badge (the one that displays Test: passing / Test: failing) had a different left side color from all the other badges. With this commit, a badge from the shields.io website is used, standardising the badge styles.
Comparing the change:

Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / ...
Thanks. I kind of prefer us to use GitHub's official badge. I have more faith in their ability to query their infra's runs more efficiently than a 3rd party. I won't block, but wonder what other maintainers think.
Good catch on frozenset's missing load_address operation @dense jungle , I added it but I can't seem to write a test for it..?
---------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------
run-python37.test:6: error: Module "typing" has no attribute "FrozenSet"
run-python37.test:74: error: Name "frozenset" is not defined
other.py:49: error: Name "frozenset" is not defined
============================================================== short test summary info ===============================================================
FAILED mypyc/test/test_run.py::TestRun::run-python37.test::testRunDataclass
Does mypy[c]'s test suite run against a custom typing and builtins or something?
yup, mypyc does use its own typing.pyi and builtins.pyi >.<
every mysterious problem with mypy tests can be tracked back to the fixtures
I updated the PR. PTAL
including this one it sounds like π
I just stole a bunch of stubs from typeshed to make frozenset work
I think we'll be able to use the latest mypy[c] once this fix is merged, unless another regression is awaiting us 
weird that the __annotations__ turn into set instead of set[str]. does mypyc do that to all generics?
mypyc/irbuild/classdef.py lines 149 to 157
def create_non_ext_info(self) -> NonExtClassInfo:
non_ext_bases = populate_non_ext_bases(self.builder, self.cdef)
non_ext_metaclass = find_non_ext_metaclass(self.builder, self.cdef, non_ext_bases)
non_ext_dict = setup_non_ext_dict(self.builder, self.cdef, non_ext_metaclass,
non_ext_bases)
# We populate __annotations__ for non-extension classes
# because dataclasses uses it to determine which attributes to compute on.
# TODO: Maybe generate more precise types for annotations
non_ext_anns = self.builder.call_c(dict_new_op, [], self.cdef.line)```
There's a todo about that in the code actually :)
ah ok. I asked because you added a testcase doing this. If it's a general mypyc behavior it's fine, but if set behaves worse than e.g. list in this regard we should fix it in your PR
sounds like it's not specific to set/frozenset, so we can save this problem for another day
wait a sec, this code is crashing at runtime even with the patch applied
from typing import Set, Type, TypeVar
T = TypeVar("T")
def wat(a: Type[T]) -> Type[T]:
return a
@wat
class NonExt:
s: Set[str] = {"a", "b", "c"}
does that work with a different annotation?
I imagine mypyc's support for class decorators is probably patchy in general
nah, I just forgot to activate my virtual environment 
β― python -i -c "import test"
>>> test.NonExt.__annotations__
{'s': <class 'set'>}
seems like all non-extensions classes (which include dataclasses AFAIK?) have a less precise annotations
β― python -i -c "import test"
>>> test.Ext.__annotations__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Ext' has no attribute '__annotations__'
lol and apparently extension classes don't even have __annotations__
To answer your question, yeah this is general mypyc behaviour, also applies to list for example
β― python -i -c "import test"
>>> test.NonExt.__annotations__
{'s': <class 'list'>}
Does mypy have a somewhat regular release schedule or are we going to be waiting for an indeterminate amount of time for the next release?
Oh and thank you for the review!
@dense jungle FYI I've been waiting for you to write documentation explaining an exception to the stability policy: https://github.com/psf/black/pull/2874#pullrequestreview-888107240
I'm alright with doing it myself, but you write better than me :)
Output requested me to file the attached bug:
Hi, would someone here, preferably a PyCharm user, by any chance has a spare moment to review a PR with improvement of Black integration docs? Namely the use of BlackConnect plugin, which in my opinion is a production-ready and awesome π https://github.com/psf/black/pull/3150
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if 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 `...
I agree with this change.
Well done, reads very well. Thanks!
re β
>>> import sys
>>> import subprocess
>>> sys.stderr.encoding
'utf-8'
>>> subprocess.run(["python", "-c", "print(__import__('sys').stderr.encoding)"], stderr=subprocess.PIPE)
cp1250
CompletedProcess(args=['python', '-c', "print(__import__('sys').stderr.encoding)"], returncode=0, stderr=b'')
For stdout to get properly encoded, sys.stdout/err.buffer.write(string.encode()) can be used
in case of click.echo, sys.stdout/err.buffer is used automatically if passing bytes to it rather than str
so doing click.echo(string.encode()) would do the trick
I'm not sure in how many places black uses unicode characters, it might be enough to alter the out() function to encode what it's passed
Pretty sure that'd break some environments where they patch STDOUT/ERR
huh?
The buffer attribute isn't required, I suppose we could fallback to what we're doing right now if it's missing tho
getting binary stream is abstracted by click
I don't know if it uses .buffer specifically
Ah yeah. I'll (maybe) look into it tomorrow. It's 12:08 over here π
Currently, the following error message is produced if Black fails to format a file:
error: cannot format foo/bar.py: Cannot parse: 1187:8: text = "xyzzy"
Oh no! π₯ π π₯
1 file failed to reformat.
Modern editors support the file:line syntax, and even some of them the file:line:column syntax.
For example, Sublime Text:
$ subl -h
...
Filenames may be given a :line or :line:column suffix to open at a specific
location.
Please, change the error messa...
turns out mypyc was missing LoadAddress ops for quite a few built-ins, python/mypy#13078
one IRbuild test is failing though, not sure why yet
ah
Expected:
...
return r0
def f(c):
c :: __main__.C
r0, r1 :: int
r2, r3, r4 :: object (diff)
r5 :: str (diff)
r6, r7 :: object (diff)
L0: (diff)
r0 = c.__neg__() (diff)
r1 = c.__invert__() (diff)
r2 = load_address PyLong_Type (diff)
r3 = PyObject_CallFunctionObjArgs(r2, c, 0) (diff)
r4 = builtins :: module (diff)
r5 = 'float' (diff)
r6 = CPyObject_GetAttr(r4, r5) (diff)
r7 = PyObject_CallFunctionObjArgs(r6, c, 0) (diff)
return 1 (diff)
Actual:
...
return r0
def f(c):
c :: __main__.C
r0, r1 :: int
r2, r3, r4, r5 :: object (diff)
L0: (diff)
r0 = c.__neg__() (diff)
r1 = c.__invert__() (diff)
r2 = load_address PyLong_Type (diff)
r3 = PyObject_CallFunctionObjArgs(r2, c, 0) (diff)
r4 = load_address PyFloat_Type (diff)
r5 = PyObject_CallFunctionObjArgs(r4, c, 0) (diff)
return 1 (diff)
it was expecting the old way of looking up builtins.float
ugh, diff-shades got cancelled on https://github.com/psf/black/pull/2874 because I pushed a changelog only commit
is it worth rerunning CI to run it?
the test workflow doesn't have the concurrency limit (yet!) and it seems to be passing on the merge commit
I'm wondering if it would be worth it in the end to rename T: design to T: code style or simply T: style
I get the feeling it's not obvious to issue openers their code style issue should use that label
https://github.com/psf/black/runs/7219918686?check_suite_focus=true OK the xdist bug still exists apparently. I triggered a rerun... hopefully it passes!
It's great to see a simpler and better way of using Black in IntelliJ IDEs :tada: Similar to @cooperlees, I don't use IntelliJ IDEs so I can only really look at the words themselves. Glad to see some happy IntelliJ users!
Thank you for the PR, I just have some phrasing suggestions.
Description
Fixes #3129: an infinite loop when using #fmt: on/off on lines with unmatching brackets.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
!e import random
prisoners = ([i for i in range(0,99)])
#creates list of prisoners numbered 0-99
shuffled_prisoners = random.sample(prisoners, len(prisoners))
#randomizes prisoner list
shuffled_list = random.sample(prisoners, len(prisoners))
#randomizes prisoner list to get the best possible random boxes
boxes = [(k, v) for k,v in enumerate(shuffled_list)]
#creates a linked list of tuples of random numbers
def main(prisoners, boxes):
"""Takes prisoner list and linked list representing boxes. Records and returns the final results"""
count = 0
final_freed_prisoners = 0
for prisoner in prisoners:
prisoner_num = prisoner
the_next_num = prisoner_num
print(f"Prisoner {prisoner_num}:\n--------Try")
outcome = prisoner_loop(prisoner_num, the_next_num)
count += 1
if outcome >= 1:
final_freed_prisoners += 1
else:
print(f"-------------XXX\n\n")
return print(f"\n*******{final_freed_prisoners} prisoners found their number********")
def prisoner_loop(prisoner_num, the_next_num):
"""Takes in prisoner number and the number 'inside' the box to map it to the next box, if prisoner finds box with his number returns 1 else 0"""
freed_prisoners = 0
for next in range(50):
next_num_tup = boxes[the_next_num]
the_next_num = next_num_tup[1]
print(next_num_tup, " -- ", next + 1)
if the_next_num == prisoner_num:
freed_prisoners += 1
print(f"------------!!!\n")
break
else:
continue
return freed_prisoners
if name != 'public static void main(String[] args)':
main(shuffled_prisoners, boxes)
@foggy ivy :white_check_mark: Your eval job has completed with return code 0.
001 | Prisoner 26:
002 | --------Try
003 | (26, 49) -- 1
004 | (49, 46) -- 2
005 | (46, 1) -- 3
006 | (1, 65) -- 4
007 | (65, 23) -- 5
008 | (23, 97) -- 6
009 | (97, 37) -- 7
010 | (37, 39) -- 8
011 | (39, 0) -- 9
... (truncated - too many lines)
Full output: too long to upload
oh crap ya there were a ton of lines i forgot...
any way to get the output to lineup better?
it's making me crazy!!!!!!!!!!!!!!!
oops sorry wrong room
Describe the style change
When splitting long string literals in Black's --preview Improved string processing style, add parentheses around implicit string concatenations to increase readability in certain contexts.
"certain contexts" include:
- Function parameters
- Sequence elements
Examples of unformatted code
flash(
'None of the email addresses or domains you entered are valid',
...
Implementation-wise this is good to go[^1] (minus all 'em merge conflicts >.<), but I need to catch up all of the discussion around docstrings and newlines (and probably quote placement too) before approving the PR as a whole.
Also, once we settle on a style, could we put it in the future code style documentation? I know this is minor, but as we're trying to keep Black relatively stable, we should be explicit when we do change the style.
[^1]: I love the refactor, it makes EmptyLineT...
anyone had trouble with black producing code that violates pycodestyle e125? I found this ticket: https://github.com/PyCQA/pycodestyle/issues/126
I don't remember seeing a ticket about E125 in the psf/black issue tracker, but perhaps I'm forgetting something.
Do you have a demo input?
one sec
maybe it was a false alarm or I hadn't saved my file
Black insists on the following transformation:
async def _get_session_id(
auth_header: str | None = Header(
None,
alias="Bearer",
description="Access token from the auth endpoint.",
),
) -> UUID:
...
... into:
async def _get_session_id(
auth_header: str
| None = Header(
None,
alias="Bearer",
description="Access token from the auth endpoint.",
),
) -> UUID:
...
Isn't that strange? I don't see a reason for the line break ~ the line's not too long
that doesn't crash?
I wouldn't expect Python's syntax to be that forgiving to newlines in that place without parens
I guess it is, huh
either way, it is a strange wrapping behavior for sure
within parentheses you can put newlines wherever you want
I just didn't think that would apply in the case of function def
agree this isn't great formatting though
it's implemented in the tokenizer, so it's just wherever there are parentheses
The # fmt: off/on/skip might be the most hacky and impossibly-to-maintain complex feature of Black. Writing any sort of robust code here is challenging. This is definitely a step forward, but there's a wart that I'm not sure how to resolve.
My suggestion is to just fix the weird formatting issue as it involves a (IMO) valid use of # fmt: off/on and let the other usages break since they don't use it properly. OTOH, there might be cases with valid usages of # fmt: off/on` that break by...
Are there any beginner-friendly open-source Python projects?
i didnt want to open an issue for this cause i might be doing something wrong, but I can't get --extend-exclude to work correctly when using pre-commit
the command I ran on terminal was: black -l 99 --extend-exclude auvsi_suas ., which correctly excluded all python files in server/auvsi_suas
using a basic config on pre-commit doesn't work the same way, and reformats all files within server/auvsi_suas that need reformatting
repos:
- repo: https://github.com/psf/black
rev: 22.6.0
hooks:
- id: black
args: [-l, '99', --extend-exclude, auvsi_suas]
language_version: python3.10
am I specifying arguments incorrectly? I tried using strings on all arguments, joining them together, etc.
the -l line length parameter works as intended, but --extend-exclude does not
which leads me to think it's caused by pre-commit passing in file names differently...
any ideas?
i've even tried using args: [-l, '99', --extend-exclude, \s*auvsi_suas\s*] to match all characters in the filename, but it still doesn't seem to work in pre-commit
Ours for one! Although our contributing docs could be way better (matter of fact I'm rewriting them right now)
!contribute -- You could also try contributing to one of the Python Discord projects, they tend to be more beginner friendly than us.
Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!
Projects to Contribute to
β’ Sir Lancebot - our fun, beginner-friendly bot
β’ Python - our utility & moderation bot
β’ Site - resources, guides, and more
Where to start
- Read our contribution guide
- Chat with us in #dev-contrib if you're ready to jump in or have any questions
- Open an issue or ask to be assigned to an issue to work on
Yea... the problem is that pre-commit passes the filepaths directly to hooks. Black ignores --include --exclude and --extend-exclude for filepaths given directly via the command line as they only really make sense for file discovery.
You can either use pre-commit's own exclude configuration, or if you just want to make Black work standalone and via pre-commit, you can use the --force-exclude option instead (I can't remember whether it clears the default excludes, but IIRC it doesn't, so it should be like --extend-exclude, but all of the time, no exceptions)
And using that, I can just specify the folder name, and it processes that within the path?
e.g. specifying auvsi_suas for server/auvsi_suas/client/file.py
I think so
not entirely sure how pre-commit's exclude works, but that should work for Black's force-exclude
oh wait, that's a subdirectory, you may have to do server/auvsi_suas/ or .*/auvsi_suas/
Where do i go to contribute
Description
Change the error report style to file:line:column to make it parsable for external editors etc
Fixes https://github.com/psf/black/issues/3157
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Seems fine, but I'm not quite sure about the punctuation. I'll let Jelle make the final call if this is missing a couple commas, but I think it is.
Thanks for the PR!
SGTM. Thank you for tackling this bug!
P.S. you need to add the closing keyword before each issue you'd like to close automagically

What is this channel
Hi @dense jungle, not sure what went wrong but can you close https://github.com/mypyc/mypyc/issues/924 and https://github.com/mypyc/mypyc/issues/935 please?
For example, we get failures if we try upgrading mypy.fswatcher.FileData python/mypy@f6332f5 mypy.modulefinder.SearchPaths python/mypy@3bb691c Also ref python/mypy#12708 Error manifests as a KeyErr...
I lack that power
the mypyc repo is separate and I have no permissions there
I'm trying to get somebody to give me access
Description
This PR resolves #3159. It adds parentheses around implicit string concatenations when it's inside a list, set, or function call.
Implementation notes
Looking at the order of the transformers here, we need to "wrap in parens" before string_split runs. So my solution is to introduce a "collaboration" between StringSplitter and `StringParenWrapp...
If anyone with async know how is looking for a (hopefully simple) issue to contribute a fix for, psf/black#3110 is it
It's the real-time communication channel for black, the uncompromising code autoformatter for Python. See the channel description for more ^^
Sorry for taking so long to get back to you, but if you want to contribute to Black, I'd recommend 1) reading https://black.readthedocs.io/en/latest/contributing/the_basics.html and 2) looking at the issue tracker for any issue labelled with "good first issue"
... if that flies over your head, I suggest instead taking a look at the sir-lancebot Python Discord project which is a fair bit easier to contribute for beginners
Disclaimer: I've seen pip and mypy use release planning issues. I've got a lot of free time for the time being so I'm curious to whether they would be of any benefit for this project (especially since our development is quite casual). FWIW I don't expect this to be as active as those seen in mypy.
Also, since I'm tentatively assuming I'll be the RM, I'm using a release milestone (https://github.c...
Thanks for this. Reading others comments, I agree people should just use pyproject.toml black config to exclude directories rather than the CLI. Here is an example of how we even do it with black on the black repo: https://github.com/psf/black/blob/main/pyproject.toml#L12
I think due to this should we close this PR as we already have this documented in black docs. If you feel it could be better I'd take a PR improving that.
-
= 3.10 add a warning that
get_event_loopwill not automatically create a loop - Move to explicit API
Test:
python3.11 -m venv --upgrade-deps /tmp/tb/tmp/tb/bin/pip install -e .- Install deps and no blackd as aiohttp + yarl can't build still with 3.11
- https://github.com/aio-libs/aiohttp/issues/6600
export PYTHONWARNINGS=error
cooper@l33t:~/repos/black$ /tmp/tb/bin/black .
All done! β¨ π° β¨
44 files left unchanged.
Fixes #3110
Descrip...
setup.py line 121
"Programming Language :: Python :: 3.6",```
If you call new_event_loop rather than get_event_loop/asyncio.run then the event loop isn't set which means the ChildWatcher isn't configured
So you should use get_event_loop on 3.6 and asyncio.run on 3.7+
All that effort why didnβt you just do the PR? LoL
I just hate all the ugly if version everywhere. With how we use asyncio is ChildWatcher even of benefit here
Do the PR?
Is it possible to configure black that way that it always places optional commas like here?
@app_commands.rename(
user="nutzer",
case="fall",
)
``` (The comma after `"fall"` is not needed)
hm we can probably drop 3.6 now?
I looked. We still have a lot of 3.6 downloads
I havenβt read what our stable policy states about dropping major version support.
The magic comma is my least liked part of black - But I get it
I just always add when developing
Good morning. What's even the benefit of ChildWatcher? I'm out of the loop (heh) on async stuff.
It's if you're using asyncio.create_subprocess_exec etc
There's actually a bunch of stuff that asyncio.run does that new_event_loop doesn't, and it looks like you'll be able to get rid of a lot of the stuff in concurrency.cancel and concurrency.shutdown
I have written basically zero async code so I'll defer to Cooper (and @austere lava if he's around) for that
I can take a look in a few
Is there a plan to drop (running on) 3.6? I thought there was an issue about it, then you don't need the conditional for asyncio.run
I know you don't follow semver in black but still I feel like these kind of changes should be deferred until 23.0 same as with style changes.
Not that I use 3.6 for anything myself though so I can't really advocate for keeping that alive in 2022 :P
hi
There's no official plans. I don't think there's even an issue about dropping 3.6 yet :p
Well eventually our deps will stop supporting it π
Plenty of our deps already don't support it, I've been keeping track. Lemme pull up my list
The snippet you tried to send was too long. Please see #bot-commands for the full snippet.
As long as those deps properly declare minimum python version, pip will resolve it
Hopefully not in too long time
Yeah, as long as we don't bump the minimum requirements for these deps, we should be fine.
If by fine you mean not immediately breaking, yeah. But bumping the minimum reqs is a good thing. Not being able to do it is bad
We don't have a reason to bump the minimums right now though, but you do have a point.
I think 3.6 should go in 23.0 too. And we amend the stable policy to dictate our plans there if others agree.
Well would be 23.1
I'm not sure if the stability policy mentions Python support at all.
AFAIK the closest equivalent we have in the docs is this FAQ entry https://black.readthedocs.io/en/stable/faq.html#which-python-versions-does-black-support
the stability policy is explicitly only about formatting output, not anything else
Dropping 3.6 in the 23.0 release seems reasonable though
with Python's yearly cadence that means we can drop a version every year
So a pedantic reading of that section says you could drop parsing 3.6 without a deprecation cycle, but can't drop running on 3.6 without a deprecation cycle
I looked at the PR and seems fine to me. @red sedge's suggestions make sense, we can improve the code even more. IMO they can go in a separate PR. I'll comment
So re. psf/black#3141, there's two ways of fixing it. A) we don't move the closing quotes if a single quote character is used, or B) we normalize ' / " to ''' / """ respectively allowing the buggy logic to "just work"
src/black/linegen.py lines 330 to 331
# We could enforce triple quotes at this point.
quote = quote_char * quote_len```
I think this PR should call asyncio.set_event_loop(loop) and then asyncio.set_event_loop(None) in the finally
Ah I can't ```suggest on the finally block
https://github.com/psf/black/blob/main/pyproject.toml#L39 you could also enable filterwarnings=['error', ...] here so you don't get caught out by deprecation warnings in the future
pyproject.toml line 39
"incompatible_with_mypyc: run when testing mypyc compiled black"```
Oh yeah lol
of course you show up in the one issue I'm looking for :p @red sedge
it's almost two years old :o
Hmm, what's the status on removing the two-format-pass hack? I'd love to get rid of it if we can. Our error handling isn't built for it and it makes debugging Black more annoying >.<
I know we have a few test cases in the test suite, but I wonder if I still have my old script that tested Black against the many cases I extracted from the issue tracker.
Oh my, I found the issue data JSON, although I have no idea where the testing script is
I FOUND IT
This code is so awful, but it still works somehow.
Cases summary:
0 failed, 71 passed, and 0 were invalid
Failed cases breakdown:
0 failed due to instability and 0 failed due to invalid output
Remember this output lol?
Case summary:
4 failed, 78 passed, and 0 were invalid
Failed cases breakdown:
4 failed due to instability and 0 failed due to invalid output
hmm, removing the two-format-pass hack does show we still need it, sadly :(
--- first pass
+++ second pass
@@ -31,13 +31,11 @@
for s in (0.0001, 0.1, 1.0, 10.0, 1000.0, 100000.0)
for sign in (1.0, -1.0)
)
),
(),
-) + (
- (0.0, 0.0, 0.0),
-)
+) + ((0.0, 0.0, 0.0),)
interesting failure mode for psf/black#2074
--- source
+++ first pass
@@ -1,7 +1,7 @@
def some_function(self):
- ''''<text here>
+ """ '<text here>
<text here, since without another non-empty line black is stable>
- '''
+ """
pass
--- first pass
+++ second pass
@@ -1,7 +1,7 @@
def some_function(self):
- """ '<text here>
+ """'<text here>
<text here, since without another non-empty line black is stable>
"""
pass
lol this should be simple enough to fix
OK failure #3 is of the same class as the last one. Failure #4 is another trailing comma instability case (I think?)
--- source
+++ first pass
@@ -1,4 +1,7 @@
class Visitor:
def check(self):
- if a == 's':
- assert type.type.type.names == [self.typemap["array"], self.typemap["char"]], line + f"{var} initialization type mismatch"
+ if a == "s":
+ assert type.type.type.names == [
+ self.typemap["array"],
+ self.typemap["char"],
+ ], (line + f"{var} initialization type mismatch")
--- first pass
+++ second pass
@@ -2,6 +2,8 @@
def check(self):
if a == "s":
assert type.type.type.names == [
self.typemap["array"],
self.typemap["char"],
- ], (line + f"{var} initialization type mismatch")
+ ], (
+ line + f"{var} initialization type mismatch"
+ )
hmm @dense jungle while fixing some docstring bugs, I noticed --skip-string-normalization doesn't stop black from normalizing docstring prefixes
β― black wat.py --diff --color -S
--- wat.py 2022-07-13 18:07:36.858247 +0000
+++ wat.py 2022-07-13 18:08:02.246896 +0000
@@ -1,3 +1,3 @@
def wat():
- F"""a"""
+ f"""a"""
pass
would reformat wat.py
should I fix that? technically it would be permissible under the exception we recently added to the stability policy since it wouldn't affect formatted codebases
Also of course it was me who introduced this bug ... https://github.com/psf/black/pull/2285/files#diff-98d222e4d1eed36d13bf2de2b3685fd3fbe65ff82450f30b77bfc11916cee76dR229
part of me wants skip-string-normalization to only apply to quote style, not the prefix
since nobody really complains about the prefix
well we're inconsistent in that regard Β―_(γ)_/Β―
I agree though, no one really complains about the prefix.
I'd prefer to fix this only in preview mode. It's technically allowed under the stability policy, but I'd prefer to use the new exception only for really critical issues like dropping comments
.. except for MagicPython's capitial R, but I don't see us removing that exception anytime soon
The conditionals involved is going to be such a pain but that makes sense.
<!--
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
... as doing so is invalid. Note this only fixes the preview style since the logic putting closing docstring quotes on their own line if they violate the line length limit is quite new.
Fixes #3141.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
Hi @dense jungle , sorry to bother you again today, but I'm waiting for your approval on https://github.com/psf/black/pull/2874. You can just check the changes since your last review as I didn't force-push the branch and you've already approved it.
(i.e. make sure I didn't mess up my changelog entries)
finally!
Description
I added a warning message just below the first paragraph noting that blackd should not run as a publicly accessible server.
Checklist - did you ...
- [yes ] Add a CHANGELOG entry if necessary?
- [yes ] Add / update tests if necessary?
- [yes ] Add new / update outdated documentation?
Description
The former was a regression I introduced a long time ago. To avoid changing the stable style too much, the regression is only fixed if --preview is enabled.
*annoying enough, as we currently always enforce a second format pass if changes were made, there's no good way to prove the existence of the docstring quote normalization instability issue. For posterity, here's one failing example:
--- source
+++ first pass
@@ -1,7 +1,7 @@
def some_function...
The current consensus is to remove Python 3.6 support for running Black as part of 23.1.0 (January 2023). Here's what needs to be done:
- [ ] Clean-up our asyncio code with the QOL features added in 3.7 (cc @ graingert and @ zsol when 2023 is closer)
- [ ] Remove Python 3.6 from CI
- [ ] Remove Python 3.6 from setup.py (metadata, etc.)
- [ ] Remove the
dataclassesbackport dependency since 3.7+ always has it - [ ] Update the `assert sys.version_info >= (3, 6, 2), "black requ...
- [ ] Remove the
I've gone ahead and made the changes I suggested to demonstrate what they look like ^^
Thank you so much for your contribution! This project is only possible by contributions like these :black_heart:. You're awesome, @Panther-12. Lemme know if you'd like another issue to work on! Also if you have some feedback on your contributing experience to share, please comment on GH-2238.
8900e3a Add warning to not run blackd publicly in docs ... - Panther-12
Description
The black config docs provide an example for configuring --extend-exclude in the pyproject.toml as shown below.
extend-exclude = '''
# A regex preceded with ^/ will apply only to files and directories
# in the root of the project.
(
^/foo.py # exclude a file named foo.py in the root of the project
| *_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
)
'''
Using the configuration verbatim results in the fol...
9aa33f4 Move to explicitly creating a new loop (#3164) - cooperlees
3.10 will also raise this warning, it might be worth running pytest with filterwarnings = ['error', ... so that these deprecation warnings are discovered promptly
_Originally posted by @graingert in https://github.com/psf/black/issues/3110#issuecomment-1147917026_
If I get a concept ack on this I'll try and whip up a PR
ad5c315 Actually disable docstring prefix normalization... - ichard26
b0eed7c Fix typo in config docs for --extend-exclude (#... - onescriptkid
I'm inclined to reject psf/black#2527, thoughts?
(either way, Shivansh is quite busy and the PR is very stale so I doubt it'll ever see the light of day)
I'm planning on joining some mypy folks on the Europython sprint tomorrow
Apart from https://github.com/psf/black/issues/2845 is there anything else that would be good to resolve with them?
Cc @solid adder in case you had something else in mind
There's also this which might be the same?
https://github.com/psf/black/issues/2867
uhhh, I could try compiling black with the latest mypyc and see what other issues are present
Jelle and I landed quite a few fixed for dataclasses and namedtuples so it shouldn't be crashing anymore (hopefully)
Hi,
Is there a setting/way to enable named expression support? (PEP 572)
I'm using it a lot and it's breaking with black apparently:
failed to parse source file AST: invalid syntax
Sample example:
if stocks := get_stocks(date):
if socket := stocks.needle():
socket.connect(peer)
lol, I got sidetracked by another namedtuple/dataclasses __annotations__ bug shantanu raised
this time with the added fun of segfaults :D
while I've actually learned some C since writing my mypyc series, this is actually my first time seriously using gdb to debug an issue π
Program received signal SIGSEGV, Segmentation fault.
insert_to_emptydict (mp=0x7ffff752ed80, key=0x7ffff766c530, hash=-156007990909362949, value=0x0) at Objects/dictobject.c:1132
1132 Objects/dictobject.c: No such file or directory.
(gdb) bt 5
#0 insert_to_emptydict (mp=0x7ffff752ed80, key=0x7ffff766c530, hash=-156007990909362949, value=0x0) at Objects/dictobject.c:1132
#1 0x000055555569a2b1 in PyDict_SetItem (op=0x7ffff752ed80, key=0x7ffff766c530, value=0x0) at Objects/dictobject.c:1542
#2 0x00007ffff7523131 in CPyDef___top_level__ () at build/__native.c:412
#3 0x00007ffff75237f8 in PyInit_test () at build/__native.c:136
#4 0x00005555557b5a49 in _PyImport_LoadDynamicModuleWithSpec (spec=0x7ffff7544820, fp=<optimized out>) at ./Python/importdl.c:164
(More stack frames follow...)
(gdb) frame 2
#2 0x00007ffff7523131 in CPyDef___top_level__ () at build/__native.c:412
412 cpy_r_r55 = CPyDict_SetItem(cpy_r_r52, cpy_r_r54, cpy_r_r53);
seems like mypyc is trying to set VTableMethod.__annotations__["cls"] to ClassIR even though it hasn't been allocated or initialized yet
right, value=0x0 is wrong
the whole way _annotations_ is handled for dataclasses/namedtuples feels a bit off honestly
https://github.com/python/mypy/blob/4479e0c2a75b7b802adf628034fa83beee9572c1/mypyc/irbuild/classdef.py#L494-L503 this is the problematic code
mypyc/irbuild/classdef.py lines 494 to 503
if typ is None:
# FIXME: if get_type_info is not provided, don't fall back to stmt.type?
ann_type = get_proper_type(stmt.type)
if isinstance(ann_type, Instance):
typ = load_type(builder, ann_type.type, stmt.line)
else:
typ = builder.add(LoadAddress(type_object_op.type, type_object_op.src, stmt.line))
key = builder.load_str(lvalue.name)
builder.call_c(dict_set_item_op, [non_ext.anns, key, typ], stmt.line)```
get_proper_type doesn't know what to do with a stringified type annotation ('test.ClassIR'), so it just returns it unchanged, and this function decides to just add a LoadAddress op for ClassIR even though it won't be allocated until later
The simple fix is to just load a constant string literal if get_proper_type returns a string, but I bet there's other issues in this logic worth fixing by reevaluating how _annotations_ is handled
Either way, I'll stop here for now and actually try to build black with latest mypyc as I said I would
value=0x0 means that it's an variable that has been zero-ed, right?
I'm totally guessing here, presumably key is also a PyObject pointer? ... I'm going to read the C-API docs now.
it means it's NULL
ah so a invalid pointer
yeah op should be the dict and key the key
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Oh look, I actually guessed correctly even though I'm not familiar with the CPython C-API haha
surprisingly black type checks OK with mypy from master without any intervention
build/__native_f4ee935d5338f3d318fb.c:75886:16: error: variable 'cpy_r_r7' is uninitialized when used here [-Werror,-Wuninitialized]
CPy_DecRef(cpy_r_r7);
^~~~~~~~
build/__native_f4ee935d5338f3d318fb.c:75509:23: note: initialize the variable 'cpy_r_r7' to silence this warning
PyObject *cpy_r_r7;
^
= NULL
1 error generated.
whelp.
from typing import Iterator
class Line:
def __init__(self) -> None:
self.depth: int = 0
class LineGenerator:
def __init__(self) -> None:
self.current_line: Line = Line()
def line(self) -> Iterator[Line]:
if not self.current_line:
self.current_line.depth += 1
return
yield Line()
I've minimized the reproducer to this so far.
https://github.com/python/mypy/commit/3c0409203a59eccb0e04caca7bef97c3e1e83ba7 is the first bad commit.
Sooo I tried compiling Black with the latest mypyc and I ran into this issue: https://github.com/mypyc/mypyc/issues/941
This issue has one heck of a title :)
Wow thanks for digging
Hello! I'm Anika Roy and I'm a beginner in open source and I'm trying to make my first contribution.I found a issue i think i can work on,could someone help me out by telling the prerequisites for this,what i should read up and try before starting with it?
Hey @surreal valley π have you read this? https://github.com/psf/black/issues/2560#issuecomment-1183920300
Description
fixes https://github.com/psf/black/issues/3171
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
With https://github.com/python/mypy/pull/13144 black now compiles with mypyc
Oh neat! I have no idea how keepalives or refcounts work in mypyc yet π
I've been looking a lot at irbuild.classdef for other bugs
keepalives are a bit of a mess IMO
Thanks @austere lava!
but I've only gotten acquainted 3 hours ago π
np π I chatted with Jukka and he said they might be interested in CI making sure black compiles with mypyc @ HEAD
so I'll look at throwing something together now
If you need help lemme know, but either way that sounds great
do you know an easy way off the top of your head to run our tests against the binary wheel?
coz compiling is one thing, ideally we'd also not crash
so uhh for cibuildwheel I cheat and I don't run the full test suite because it requires multiple runs and I don't know how to make tox use a compiled wheel for that
where's the cibuildwheel config?
I assume we run this from some github action but can't find it in .github
ooooh your own repo
Yea, I still need to integrate it upstream π
π need help? I have some time today and tomorrow
IIRC I've made the necessary changes locally, but I need to test them because I'm not deploying 100+ lines of CD configuration without testing
Which is mostly a matter of pressing some buttons and making a sacrifice to the "build correctly on first try" gods :p
Description
document filtered warnings that cannot be removed easily and move invalid escape sequence DeprecationWarning to those tests that need it
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
are these test cases intentionally triggering the syntax deprecation warnings? https://github.com/psf/black/pull/3175/files#r922679150
As soon as https://github.com/hauntsaninja/mypy_primer/pull/41 is merged, mypy will get CI signal on if mypyc can compile Black (and run our test suite)
so hopefully no new mypyc PRs will break our ability to release
yes i did π i looked through the resources mentioned too.I was just wondering if there was something else i should look up too before i startπ
See https://github.com/ichard26/black-deps-ci/runs/7374216061?check_suite_focus=true. We can either bump the lower bound requirement for aiohttp, or we can reuse the approach taken in https://github.com/psf/black/pull/2974/ for a similar issue.
cc @zsol we should probably configure pytest to not error out on warnings when running under mypy_primer since it'd be pointless busywork and noise for them.
Gah, I didn't think before talking and made an incorrect assertion mainline CI is going to fail. I forgot that ichard26/black-deps-ci is using the master/main versions of deps π
@bright glacier also it's a bug in aiohttp
wat
They're not closing their transports correctly
Yeah I can see the ResourceWarnings, but AFAIK pytest isn't failing because of that. It's failing on
FAILED tests/test_blackd.py::BlackDTestCase::test_blackd_diff - DeprecationWarning: Middleware decorator is deprecated since 4.0 and its behaviour is default, you can simply remove this decorator.
Oh wait I was looking at the BaseEventLoop.__del__
And misdiagnosed it
The resource warnings will fail pytest on python 3.8+
No clue, I'd have to look at the blame. My guess is that it was not intentional, but merely a byproduct of the commit author trying to stress test our parser and/or formatting logic
It's line 682
Got it,thank youππ»
Hello,
I am trying to use black as a library and so far so good. It is easy to just call black.format_str(code_block, mode=Mode()) but I would like to pass a configuration as an argument as well. Is there any way I can create Mode object from a pyproject.toml file? Preferably I would like not to parse the file myself and create Mode object manually. So far I could find anything related to such thing inside the source code.
TLDR: I would like to call black.format_str in a way t...
Version:
python-black 22.6.0-1
Distro:
Arch Linux
To reproduce the error:
/usr/bin/black - <</dev/null
I think this is wrong behavior. It makes it harder to use formatting tools in text editors such as https://github.com/mitranim/sublime-fmt, because the tools relies on the correct streams.
hi ππΌ
first time chatting here
is this a good place to ask for PR review timeline expectations from maintainers, since i've sent a few PRs earlier?
it seems that all of these PRs have merge conflicts?
the conflicts are all in CHANGES.md which changes frequently, they are also trivial to resolve
so i hope to get a better idea of when they can be reviewed before updating
we just adopted towncrier for our own project, it was pretty trivial to set up
DisnakeDev/disnake#600
don't let the massive diff confuse you 
and for the concerns of getting change notes in alpha documentation: sphinxcontrib-towncrier
sorry I've been busy π¦ I'll try to take a look
understood, and no worries! as long as they will be reviewed. and i hope to send more contributions once they are done.
also, i'm more like to see a review on #3162, if you only have the time to take a look at one of them.
oh yeah sorry I've been dealing with some personal troubles so I've been out of it for code reviews lately
will try to take a look on one of them at least today
again, no worries! take your time π
I'd suggest refactoring generate_ignored_nodes into a few subfunctions because it's getting pretty hard to follow the logic, but other than that, LGTM. Great work and thank you very much!
@dense jungle both of these fmt: skip PRs are technically changing the stable code style, is that OK?
I'd hate to have to lock these improvements under --preview, would be clunky for both us developers and users
only if it fixes a crash
OK, both do fix crashes (technically psf/black#3158 fixes an infinite loop, but that seems major enough similiar to a crash)
although psf/black#3148 also fixes some non-crashing format issues (mostly related to comments being moved or deleted) along side with some instability errors
PTAL for both. I won't merge until you are fine with them from a stability standpoint.
I'd love if you could do code reviews too, but I'm confident enough in them that it shouldn't be necessary. Policy reviews are all I need to land them if we're getting close to the release deadline
wouldn't that fall under the recent change to the policy? (the changes only affect formatting unformatted code)
Yes, they would but you wanted to keep our uses of the exception as minimal as possible hence why I asked for comment.

oh I see, I think fixing bugs where we eat comments is definitely a good use
comments should not be eaten
imagine using an exception that was recently changed right away
we did, for another bug where we also ate comments π
I didn't actually know that the PR fixed that behaviour until after asking you for comment. I did not check the linked issues π
i mean
eating comments is actually smart
because it enforces a coding style where comments can never be out of date

oki i'll see myself out now
I just assumed that they would change the formatting output of code using fmt: skip to something way less broken / janky
Also, thank you for the reviews Jelle!
Now this release is basically entirely held up on things I've assigned to myself haha. Might see if I can delegate some of the items.
thank you both for your reviews! i'll update the PRs per comments and resolve the conflicts tomorrow.
Running Black --check on parser test code as documented in PP-617 on a relatively new Macbook takes 4.45 minutes.
To Reproduce
time python3 -m black --check test.py
Expected behavior
Processed in a couple of seconds.
Environment
Macbook pro 2019 running Linux Mint 20.
CPython 3.9.6
Black 22.6.0
Additional context
Excerpt from PEP-617 :
The first timings are for our canonical test file, which has 100,000 lines endlessly repeating the following thr...
I'm not able to reproduce this one
Oh. The file they're running are those three lines repeated several times
I'm not sure how specific it is to the test case given. A file containing 100k "1"s runs quite slow with black
i wonder if it's the parser or the formatter
Ditto 100k "()"s, becoming slower the more nested the brackets are
Hey @fast heart!
It looks like you tried to attach file type(s) that we do not allow (.prof). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
thanks mypyc π
π
what's the best way to trigger a rerun of the failed actions on a PR (due to flakiness)? i can git commit --amend and do a forced push, but i want to avoid it if possible
you can push an empty commit
you can ask a maintainer nicely. closing and reopening also works
if you link me the PR I can push some buttons
could you please push the buttons on https://github.com/psf/black/pull/3162 and https://github.com/psf/black/pull/3148 ? π the failures are coveralls server errors
Description
This PR resolves #3159. It adds parentheses around implicit string concatenations when it's inside a list, set, or function call.
Implementation notes
Looking at the order of the t...
done for 3162. 3148 still has a few jobs running, I'll wait for those and then restart the failing ones
Description
This is a tiny cleanup to make the test data filenames to consistently use underscores.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary?
- [x] Add new / update outdated documentation?
so many issues closed π
I might finally make some real ground on my issue closures π
Yay, this month's issue delta is negative! Although that will probably change by the end of the month π
https://ichard26.github.io/ghstats/ (it updates daily around 10AM EST, but I triggered a manual update)
so ambv was talking to me about how many 3.6 downloads black is getting and why it has no many 'null' python version downloads and that he's not seen anything like it on other projects, however anyio seems to also have this large proportion of weekday 'null' python version downloads
https://pypistats.org/packages/black
https://pypistats.org/packages/anyio
PyPI Download Stats
PyPI Download Stats
Are those from non-standard pip downloads? EG conda, some archival copier etc.
Some multi-line function declarations are concatenated to a single oversized line.
For example,
def freezer() -> Callable:
...
def freezer_func(
pitch,
vel,
time: float,
s: int,
t: int
) -> tuple[list, float]:
...
return freezer_func
becomes
def freezer() -> Callable:
...
def freezer_func(pitch, vel, time: float, s: int, t: int) -> tuple[list, float]:
...
return freezer_f...
π€
Hello!
How do I in django to query a value in the bank greater than 100 and less than 1000
Consider asking in #web-development
Does conda download via archive?
Anyway the trick to find out is to run the query and filter to include only the nulls and then look at the user agent
But we're both too scared of big query to do it
are you too scared of the outcome or bigquery itself?
big query itself
Is this all for asyncio.run?
what do you mean? π
oh I think it's unrelated to the mypyc fun
The discussion started with it being about 3.6 stuff
But then got onto why black was getting so many more nulls than other projects
Wonder if we can work on getting more info on what the nulls mean - I guess thatβs your plan digging into the bigdata dataset
Yeah my working hypothesis is that the user agent does have the python version in but the regex in pypistats is wrong
For automatically formatting code with black using github actions, is there a reference for getting this setup?
And comitting to the repository/PR
not really, we did get a PR for "autoblack" but we never landed it
my suggestion would be pre-commit.ci (and don't push to main directly)
we use pre-commit.ci for this for PRs on typeshed, works really well
Pre-commit seems to be it!
It's doing at least half the job, but I don't think it's pushing: https://results.pre-commit.ci/run/github/515882591/1658437211.MUgD5ZoBTnKLR_m5VbfGmg
I just copy-pasted from the typeshed configuration
you may have to give it some special permission?
Haven't been able to find it anywhere
Describe the style change
Examples in the current Black style
compare = torch.tensor(
[
[
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
...

