#black-formatter
1 messages · Page 21 of 1
sorry, it's a trait of mine
It's something with ESP I think?
Possibly
Anyway everything's going alright?
no pitchforks for me yet
Phew
It’s good to have ya’ll release to find things I take for granted etc.
@GitHub#0000
That's a webhook, not a user/bot
I know bro
@dense jungle - https://github.com/PyCQA/flake8-bugbear/commit/82107763dc9eb98904be0d2f4e8a31b01cafe687
great! I'll just close my PR
lmao
I don't know why, but I find this funny
fixed bugbear instead.
imagine running enough of the python ecosystem where you can just pick which project to fix
I'd love more maintainers for bugbear
I basically solo maintain it these days - But get good PRs from people still :d
I'll be honest only a few days ago I realised what bugbear did
I copied my flake8 plugins from a different project when I set up my env so they were there and on my pre-commit
I love B001
thank you for maintaining it
Actually just noticed that a lot of my code has been caught by bugbear
@solid adder started it
Ah, nice!
Yeah I apparently have been saved by it a lot :))
ugh
fuck this project
gimme a few minutes, I need to test something
I really wish it used spaces instead of tabs
.....
holy
UH
tldr I hate this project's formatting.
9726 flake8 problems
most of them W191
running black bumps it down to 2276 problems
Why?
.
Why
yes, it's valid - you can use additional_dependencies for local hooks
the changelog entry IDs seems a bit off: https://black.readthedocs.io/en/latest/change_log.html#b0
eg I'd expect it to be https://black.readthedocs.io/en/latest/change_log.html#21.9b0 or similar
also it seems to be missing from stable
we haven't updated stable yet, will do it later today
Here's your reminder: check release status + finalize release process
[Jump back to when you created the reminder](#black-formatter message)
going to move the stable tag now
done
hm RTD didn't update. couldn't find the place to do it in the admin UI
I pressed the button on my phone, hopefully that fixes it https://readthedocs.org/projects/black/builds/14717345/
It isn't building on push?
so... the problem is that they delete and create a stable tag
yup and RTD gets confused and rebuilds stable .. using the old stable revision
an additional rebuild clears out the issue and RTD then notices the right commit but yea it's weird
Hey all - I just started using black and felt the diff below was a little strange and was hoping someone might be able to provide some clarity, particularly as the suggested change is far longer than 88 characters and doesn't join the strings. Is this expected? If I set the line length to 80 this change isn't suggested
- print(
- f"Found {len(self.selected_str)} strings with a "
- f"minimum hamming distance of {self._min_dist}"
- )
+ print(f"Found {len(self.selected_str)} strings with a " f"minimum hamming distance of {self._min_dist}")
edit: if I set --line-length 88 the change isn't suggested either?
so what line length were you using when it collapsed the lines?
I didn't specify the line-length so I would assume the default 88
You may have had a config file somewhere overriding the default
Gotcha! Thanks! I'll try and take a look and see what I can find
Ah that's weird
Could you perhaps trigger a rebuild using the API rather than doing it manually?
...
they have a python example even
import requests
URL = 'https://readthedocs.org/api/v3/projects/black/versions/stable/builds/'
TOKEN = '<token>'
HEADERS = {'Authorization': f'token {TOKEN}'}
response = requests.post(URL, headers=HEADERS)
print(response.json())
echo $RTD_TOKEN | python -c 'exit(0 if __import__("requests").post("https://readthedocs.org/api/v3/projects/black/versions/stable/builds", headers={"Authorization": f"token {input()}"}).ok else 1)'
```Here is a more CI friendly version :D
ah, perfect lol
Finally remembered to try this, it does work
experimental-string-processing = true
Man I finally got around to setting up black to run on file save on pycharm
🤤 So nice
Describe the bug
Returning a tuple containing star operator without enclosing with parentheses leads to a Cannot parse error.
Oh no! 💥 💔 💥
To Reproduce
def apply_to_last(input, func):
*header, last = input
return *header, func(last)
# which is valid code doing this:
assert apply_to_last([1,2,3], lambda x: x+10) == (1, 2, 13)
And try to blackify...
Expected behavior
I expect it to not choke.
There is a workaround -- enclosi...
TIL return *header, func(last) is valid python
(not much to say here but I've used Black for ~3 years and I want to say a big thank you to all contributors. Terrific formatter.)
The same i have to pass in pyproject.toml to enable it? Or there is something diff?
You can enable it there, or via cli using the --experimental-string-processing option
error: cannot format black_src_error2.py: INTERNAL ERROR: Black produced code that is not equivalent to the source on pass 1. Please report a bug on https://github.com/psf/black/issues. This diff might be helpful: black_error2.log
black --line-length 130
black 21.9b0
Linux/Python 3.7.10
black_error2.log
Its the same option, i too thought it would be different, thats why i asked here
It works perfectly fine, Thank you 🙂
Describe the style change
For a function with no args, magic trailing comma lets us control how the return type looks.
However, if we add an arg, the magic trailing comma is ignored, and the return type stays on one huge line.
Instead, it should be split across lines.
Examples in the current Black style
Consider the case of --line-length 120. Length is not a factor here; in all cases, the entire definition could fit on one line.
With no arguments to def fn(), ...
Describe the bug
To Reproduce
Expected behavior
Environment (please complete the following information):
- Version:
- OS and Python version:
Does this bug also happen on main?
<!-- To answer this, you have two options:
- 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...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte any ideas why this is happening?
Just replied on the issue
idk why this is happening tho
Try debugging it. Maybe print out which file it's trying to read
kk
Once we know more we can make a change to Black to make the error more informative
i think its cause its using utf-8 characters ie emojis and its not sure about it
does anyone work with Python 3.9 while developing black?
I can't get pipenv install to run cleanly because of dataclasses
I've been trying to fix it but I hate pipenv to no end
I'll try a few more relocks but I honestly don't know how to fix it
oh man this really is painful
i tried removing aiohttp-cors but now my Pipfile.lock is full of windows-specific dependencies
src\blackd\middlewares.py:1:1: error: Module "__future__" has no attribute "annotations"
Thanks, mypy
Description
This PR removes Black's dependency on aiohttp-cors because it seems to be unmaintained and spewing DeprecationWarnings (due to the use of @coroutine decorators).
TODO
- [ ] Add a CHANGELOG entry
- [x] Add tests
- [ ] Actually remove
aiohttp-corsfromPipfile
Did we recently update flake8? I got some B904 errors on my PR (I fixed the one in blackd/__init__.py)
- seems like coveralls upload is busted
whelp 🙃
We don't pin the flake8-bugbear version in .pre-commit-config.yaml as it would have to be updated manually so I guess a new version was released recently?
... that expanded / added B904?
OK, coveralls is properly broken.
Maybe the cache got evicted and now we are just pulling down 21.9.1?
.pre-commit-config.yaml lines 23 to 27
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear]```
its not pinned and it was installed in that pr
I know
We don't pin the flake8-bugbear version in .pre-commit-config.yaml as it would have to be updated manually so I guess a new version was released recently?
Yea, looks like the cache got evicted: https://github.com/psf/black/pull/2500/checks?check_run_id=3640780012
yeah
ooh nice pr 2500
uh, how do i set up an environment for black--where's the contrib guide
nvm found it
Ugh, so maintenance-y stuff that is broken include:
- linting via flake8-bugbear
- development environment setup on 3.8+ due to the dataclasses backport
- coveralls
- probably more...
pipenv 🤢
FWIW, the development docs are pretty outdated and lacking
lol
Hey Richard, I can try to help with the pipenv issues if you have time to share what’s happening on your system
coveralls is fully borked, not related to black. Its possible to migrate to codecov tho 😉
I'm currently installing the 111 dependencies locally so I can run pre-commit in a full environment to test the flake8-bugbear on pr 2500
...
I've found pipenv to be extremely sensitive to the environment when locking. Stuff that affect the lockfile output include: 1) your current python version, 2) OS, 3) whether you have extra packages installed in the environment, 4) whether there's a totally unrelated virtual environment in the CWD, 5) caches....
fuck this is gonna take a little longer than I thought be pipenv is stupid and made my venv using 3.10.0rc2
Time to revive the poetry branch? 😄
I mean some of the stuff is pretty reasonable like OS, but why a unrelated virtual environment when I'm already in another one?
to be fair there's a good number of bugs with poetry lol
okay, remaking the venv with 3.8.12 now
yeah, you should have flake8-bugbear pinned same as with the main pre-commit hooks to have proper reproducible builds
and also because pre-commit won't reinstall
Personally I would just go pure Nox and get rid of pipenv / peotry but that's just my opinion 🤷♂️
nox?
I’ve seen bug reports on pydis projects for both poetry and pipenv, but at least poetry is faster.
Broken faster
PDM is meant to be a next generation Python package management tool. It was originally built for personal use. If you feel you are going well with Pipenv or Poetry and don't want to introduce another package manager, just stick to it. But if you are missing something that is not present in those tools, you can probably find some goodness in pdm.
It's basically tox but easier to use IMO
!pypi nox
uh?
I heard tox 4 will allow configuration through py files
huh til that if you press the e key it will automatically put the file in editing mode and make a fork
i mean congrats on your first fork
Half of the Noxfile.py is just release crap, it's a personal project so why not do some experimenting and see how much I like strong release automation ^^
Yup, although apparently it's still in beta?
okay
after a local check
I can confirm that 21.4.3 of bugbear did not show that, and 21.9.1 does
with all of them being in either linegen or init.py
The problem with pinning flake8-bugbear is that pre-commit autoupgrade won't actually bump it, but I guess pinning it is still worth it even if mildly annoying.
i mean
not pinning it means that pre-commit autoupdate won't upgrade it either, it'll just upgrade whenever 😛
however, its probably worth actually fixing these suggestions than ignoring them
src/black/__init__.py lines 947 to 950
try:
masked_src, replacements = mask_cell(src_without_trailing_semicolon)
except SyntaxError:
raise NothingChanged```
re coveralls: https://status.coveralls.io/?utm_source=embed
Welcome to Coveralls's home for real-time and historical data on system performance.
it's been down for like 16h by now
emergency database maintenance to avoid transaction wraparound
🙂 kudos to them for noticing before the actual outage started happening
transaction wraparound
what's this lol
I'm guessing integer overflow
ah
can anyone who is more knowledgeable than me with pre-commit quickly check this isn't stupid? psf/black#2481? I highly recommend reading the linked issue FYI.
Where do we use pytest-cases in the test suite? I'm currently removing parametrized and I'm wondering if I can remove any other testing dependencies.
It makes sense to me. Anthony pulled support for python 2 from pre-commit a little while back. Letting pre-commit run black on which ever version of python/pip installed it seems sane.
Though given that black behaves differently according which Python version is running it, I think it makes sense to keep suggesting to specify language_version in the docs
Hmm.. could well be an issue that's never shown itself through setups I'm familiar with. Suggesting it doesn't seem to have ill effects.
In the linked issue, they ran into it https://github.com/psf/black/pull/2430 . They want to specify their language_version, but they want to do so at a global level, which is why they asked for it to be removed from the hook.
But advising that users specify the language version, whether at a global or local level, still seems like a good idea.
Just my 2 cents, no strong opinion here though 😄
My pain meds are making me more
that usual. If there is a breaking condition to avoid, then being strict on the python version at the upstream level makes sense and the end-user can/should understand they need one more line of config if they want more control.
If the only reason is to avoid running on python2, then I don't think it's needed at all. Not in the current setup of the tools involved, at least.
Again, this is me struggling to see the whole picture but not willing to just ghost the conversation.
The hook has worked brilliantly for me, going on a year now of using it in all my projects personal and work related. "If it isn't broke" says no change is needed to me.
Exhaustion of being defensive around py2 and just wanting it to die says to nuke the line.
LOL, after pulling all that out of my foggy head you summarized it brilliantly with "hey, this is optional"
re Pipfile.lock, I'm more and more convinced we shouldn't check this in
it's supposed to make sure people's development environment is the same, but it hinders the development experience more than it helps
confession: I have never used pipenv in years of working on black
pipenv install outright fails on anything > 3.6, or god forbid Windows
I just pip install -e in some venv
hey it worked for me on 3.8.12 earlier 😠
well I can't get it to work on a completely fresh 3.7.12 or 3.9.4, it fails to install dataclasses
the only way I've *sometimes* gotten pipenv to behave in an OK manner was to do a clean clone (cause any extra files or directories could cause issues), use a python 3.6 virtual environment and maybe clear some caches ... on Linux mind you.
We should probably move to something else. I'm not keen on poetry but it sounds like it's mature enough?
Honestly I'd prefer a pip-compile + Nox setup over this current one. unfortunately pip-compile doesn't actually have a proper resolver so its lockfile generation is probably worse in terms of cross-platform compatibility. TBF I haven't used poetry nor pip-tools at all so this is just a comment on their scope and general functions.
I've used poetry without any problems personally
I liked it a lot more than pipenv, and it's much faster
0540591 add check for version in the-basics example (#2... - MarcoGorelli
Looks good with a couple of suggestions for wording
wish me good luck :)
If you’re willing to take the hit on the big diff, deleting the lock file and relooking usually produces a cleaner result (and is way quicker 🤡)
I really don't like the "upgrade the world" feature of that :p
do we depend on that pipfile lock for anything? CI?
no, just for developers locally
then 🙂 ¯_(ツ)_/¯
Poetry via pre-commit and export to requirements.txt (used with pip install -c requirements.txt) is pretty great
That is a supidely late reply, but the way pipenv is made it will fail on every single python version except the one you used to lock. So if you have a 3.9 lock file, it will fail on 3.8. If you find yourself needing that, I'd say pipenv isn't the right tool for the job. I am not 100% sure, but I believe poetry doesn't mind that? Flit would also be an option but it is pretty barebone.
also can confirm, poetry does not care.
Is this a Linux thing? Works fine on windows
Huh, I don't know, I remember it breaking on windows too
Besides the existing dataclasses issue, I did the following and none of it failed:
- Created an environment using 3.9 on my (windows) machine (I also used this for locking. It did complain about not locking dependencies for dataclasses, but that didn't seem to be a problem)
- Created an environment using 3.7 on my machine
- Created an environment using the 3.9 docker image
- Created an environment using the 3.7 docker image
As far as I can tell, it didn't hit any blocks
And I sent that premateurly lol
Let me finish the testing and get back to you in a bit
Mostly just waiting on docker to build the 3.7 image
And done, all clear
What would black do with the proposed f-string changes?
We are considering moving the f-string parsing to the grammar in CPython. This may allow (if we decide to) some new things like nesting quotes (for example: f"some text { my_dict["key"] } more text"), which currently is not possible. What do you think about this possibility?
Oh wow, cool!
Let's worry about the 3.10 grammar changes first. If whatever we doing works with the general PEG grammar, it should be easy to adapt it for 3.11 too
Yeah it looks like you'd have to intentionally break quote parsing if you import the grammar from main
It's also a style choice, eg should black alternate quote styles or force "?
Obviously if any of 3.6-3.9 is a target version then quote styles must alternate
Consistency would be nice, and you could probably throw the alternating option under the t flag
Speaking of, does that actually work? I ran into what I think is a bug with it while investigating another one a while back, but never got around to looking into it
All our options work until someone gives a concrete bug report that shows they don't
Also I don't remember what -t is. --skip-string-normalization?
Alright, I did write a report in response to another issue, I can dig it up and reinvestigate
T specifies python version
oh, --target-version
I added that option and I still don't remember the short form 🙂
Heh can’t blame ya
There are a ton of options
Hey I did write a repro 🤓
The crux of the problem was:
Running black in a python 3.8+ environment on a walrus with -t set to 37 would work, but the opposite doesn’t
Which I think is opposite of the intended behavior
I’m not sure it’s acc feasible to fix the issue on a 3.7 env, but I feel like it could be fixed on 3.8
Unless I’m fundamentally misunderstanding how that option works
I see, I understand why we do it that way but agree it's confusing
Currently you're forced to alternate quotes for the syntax to work
They're talking about parsing the {} directly with PEG in one pass to simplify the parser, but it means they have to choose to reimplement the limitations of the old parser
Which part are you replying to
happy to help 😄
just used them as a basis to write my own hooks 🙂
Does anyone have a pre-setup github actions black CI?
just to auto format on PR / Push?
that sounds like hell
The "does that actually work" part
Can you use pre-commit.ci instead?
I was referring to the -t option, I’m sure the f-string thing will work when released
Whats this channel about
It is about the uncompromising code formatter https://black.readthedocs.io/en/stable/
...
this is why I test my lint on all versions
oof
this wasn't actually black that failed, sry
not really
if you have version control, you should do that
nah ,it was local file
you can still use git to manage a project even without a server
i mean it is not a git repo
Description
Checklist - did you ...
- [ ] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
According to the docs, to install Vim plugin with vim-plug, we must use branch stable. But there is no (more ?) branch stable only a tag.
.vimrc file :
Plug 'psf/black', { 'branch': 'stable' }
When I try to install the plugin with :PlugInstall command, I have these error : Invalid branch HEAD (expected: stable).
If I modify my Vim configuration to use tag instead of branch, it works as expected (Vim ...
How to apply black for a specific PEP Code Layout.. say e501? Right now all i can find on internet docs are just full scan and apply commands.
looking for something like black —apply E501,E402 or black —apply E*
Hi, Black is not really built to do that. We aim to provide one style and enforce it all the way!
e501 is lines too long... i think you can maybe use autopep8 to do those simple things
!pypi autopep8
this is the most simple formatter
And yeah, if it's just line length that you're after, you can decrease it by calling black -l 79
but that only works if the program is already formatted with black ^
Yup 😄
there is another formatter, although I'm not sure what luck you'll have with it, but yapf
(actually it'll work with any code, but will make other changes if the code wasn't previously formatted with black)
I’m sorry i did not give you’ll context to my need. So, here is what i am stuck at. I have more than millions lines of codes that was built for good number of years. Now i have to enforce PEP8 to it, without have git push of millions lines of codes changed and deleted with one commit and PR. So I took statistics / grouped using flake8 —statistics. The plan now is to apply black (if it had option) per PEP8 code layout per commit and push all in one PR. Any help is appreciated.
why not format the codebase by parts, rather than change every single file in every single commit slightly
Commits are per PEP8 code layout, not per single file.
Oh! Have a read through "avoid ruining git blame" in our docs if you're worried! https://black.readthedocs.io/en/stable/guides/introducing_black_to_your_project.html#avoiding-ruining-git-blame
But yeah, formatting a little bit at a time would be an option. Sadly black doesn't quite support that, but it is likely coming: psf/black#1352 Not for single style choices though I'm afraid
Thx for sharing the issue ref. As you rightly said.. these issue are similar but not exactly my request.. which is -> apply black to array/list of PEP8 code layout or apply full format but split (like docker layer) each change with PEP8 and auto use git commit / git hooks feature .
So, do you recommend opening issue and discussion around this on GH? Sorry to ask, i am new here, joined few mins ago. Haven’t explored how things work yet. A quick overview or link share will be great help.
No, not really. That's not something we are willing to implement. And no worries! Welcome aboard 😄 But as I said, we like to enforce only one style, and feature lists don't quite fit that
Well the documentation site is a good place to start!
We do offer a pre-commit integration, but that would again format the whole code base
Cool, let me read the docs further first thing in the morning
TBH your best bet with those requirements is probably a different formatter.
Btw are you open for contribution of this feature? Or strict no to such option in black? 😅
Very likely strict to no such option
Tldr your suggestion is against the core philosphy of black
Most probably not 😅 but thanks for considering! If you'd like to chime in, there's a mountain of other issues on the tracker 😆
We won't add such an option. I'm not sure why you need to apply these changes one by one. Our recommendation with Black is to reformat everything at once so you're done with it.
Applying all the format at once to millions lines of code and asking for PR review, is actually a big no for any reviewer. 😅
Hence the need
¯_(ツ)_/¯
Well hopefully the range format issue will gain some traction and be implemented then, that could be your way out!
Like I said, if you want to apply to just pep8, you could try using autopep8 for a simple intial pass 🙂
!pypi autopep8
Then maybe format parts of the codebase at once, or find a way to avoid needing so many reviewers
Although gasp for other formatters advertised :D
its like, the total opposite of the spectrum of black
Black has safety checks that should make you able to reformat all code at once without worry
black is intentionally hard on your code. Like, I've legitimately formatted code with yapf which made the code extremely wonky and black reformatted it without a diff 👀
here's our functional equivalence promise
now, the one thing that may cause an issue is #3. But since you don't have any other formatting that probably won't be an issue 😆
However, it could cause issues if you have any international comments or something in your code
huh, just had to reinstall discord
okay then
Sorry I missed your message earlier, it just tried autopep8 + few of Linux commands to pass PEP8 code layout error # and details as commit message with prefix ’fix for’ and it works. Thx for the help. 🙂
Thx everyone 🙂
Have a wonderful day. Stay Safe. 🙂
Description
This PR is in response to issue #2476. It allows the black vim plugin to parse the skip_magic_trailing_comma option from pyproject.toml and act accordingly.
Checklist
- [x] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary?
I'm not sure exactly how to do this, or if it's necessary. If it is, I can try to figure it out. - [x] Add new / update outdated documentation?
Not necessary in this case. Black already claims to use `pyproject.t...
I'm working on a test suite cleanup PR. Main goals include 1) reducing test dependencies, 2) simplifying the more common test cases, 3) restructuring & reorganization. Do y'all have any other requests you'd like put in the hat?
more regression tests, maybe?
I'm not adding new tests but making it easier to add new ones 😉
has anyone ever formatted the stdlib?
Black Formatter is so nice
Technically not formatting, but I did run a pretty hefty flake setup on it
Let’s see if I can find my results
Generated >4MB of annotations
Which turns out to be just over 50K annotations
~1K of them were line length, so bumping that up to 120 left me with exactly 49,720
In summary, if you ran black over it, you’d probably end up with a completely new language
I kind of want to start up a codespace and let it run that
Because I am an idiot it is running
Let the lines be split
I don't have enough CPU cores for that 😢
You'd think so
I have a dual core APU from 2016 that boosts to 2.3 GHz ...
Alright, reaching the Tools folder
i've only not shallow cloned cpython...several times
Umh, the process isn't exiting despite having printed Reformatted setup.py, which should be the last file. Should I guess that some workers are stuck on very large files?
lmao
also i ran isort on the library 👀
i also learned about a few peps from places where black failed to reformat the code since it couldn't parse it 
ofc those were parser tests, so black failed successfully 🙂
(invalid code, black should not pass on those)
error: cannot format Lib/test/test_exceptions.py: maximum recursion depth exceeded
Oh no! 💥 💔 💥
1860 files reformatted, 149 files left unchanged, 13 files failed to reformat.
real 10m8.830s
user 27m38.220s
sys 0m9.280s```
what commit are you on?
3.9
I formatted on 3.9.7's version
codespace ➜ /workspaces/cpython (main ✗) $ git diff --shortstat
1860 files changed, 276766 insertions(+), 211327 deletions(-)```
git checkout v3.9.7
So a good 500k line diff
oh god
this reminds me
i uh
have a confession if I can find the logs
🙃
I have already formatted the stdlib, with github actions so HA
er
found it
that was a fun problem
This is a known bug, I think it's already on the tracker somewhere
I think it does something like x = x = x = x = a couple hundred times
Haha
Lmao I didn't have that bug
lmao
Assertions written as assert(condition) appear all throughout a certain code base. Can I use black to change this and nothing else all through the code base at once?
I'm afraid not, this was discussed just yesterday actually 😄 Black is a sort of all-inclusive deal
okay thanks 😄
but you can use LibCST for this
I'm pretty sure that there aren't a lot of formatter which can rewrite one specific thing-- how would you tell them what to rewrite?
Either I have forgotten everything about our file collection and discovery code or this area of the codebase is truly a mess. Given how hard it has been to write a convenience function for the associated tests, I'm leaning towards the latter. stdin_filename and include are particularly confusing :/
Why does passing None lead to different behaviour than passing the compiled default excludes with get_sources? I thought this was supposed to normalize them:
501 if exclude is None:
502 exclude = re_compile_maybe_verbose(DEFAULT_EXCLUDES)
oh right, searching for gitignore is blocked if a non-default exclude is set, ahhhhhhhhhhhhh
Describe the bug
When using only the black pre-commit hook using the default install (ie: not black[jupyter]), pre-commit throws the following error:
An error has occurred: InvalidManifestError:
==> File /Users/sam/.cache/pre-commit/repox0xprpud/.pre-commit-hooks.yaml
==> At Hook(id='black-jupyter')
==> At key: types_or
==> At index 2
=====> Type tag 'jupyter' is not recognized. Try upgrading identify and pre-commit?
Downgrading the pre-commit hook to 21.7b0 ...
Perhaps adding some comments to the code wouldn't (or cleaning it up :p ) be a bad idea 🤔
seems like a misconfigured pre-commit-config.yaml
I doubt it given the error says .pre-commit-hooks.yaml
def test_gitignore_used_as_default(self) -> None:
path = Path(THIS_DIR / "data" / "include_exclude_tests")
include = re.compile(r"\.pyi?$")
extend_exclude = re.compile(r"/exclude/")
src = str(path / "b/")
report = black.Report()
expected: List[Path] = [
path / "b/.definitely_exclude/a.py",
path / "b/.definitely_exclude/a.pyi",
]
sources = list(
black.get_sources(
ctx=FakeContext(),
src=(src,),
quiet=True,
verbose=False,
include=include,
exclude=None,
extend_exclude=extend_exclude,
force_exclude=None,
report=report,
stdin_filename=None,
)
)
self.assertEqual(sorted(expected), sorted(sources))
to ->
def test_gitignore_used_as_default(self) -> None:
base = Path(DATA_DIR / "include_exclude_tests")
expected = [
base / "b/.definitely_exclude/a.py",
base / "b/.definitely_exclude/a.pyi",
]
src = [base / "b/"]
assert_collected_files(src, expected, extend_exclude=r"/exclude/")
Anyway, this is what I'm aiming for most file collection tests. I'm not sure if this idea will hold up well enough, but hopefully it does!
.pre-commit-hooks.yaml line 17
types_or: [python, pyi, jupyter]```
tldr the jupyter type here is not accepted
oh that's probably the issue lol
I should've read the error message a bit more carefully
can use https://github.com/pre-commit/identify to determine the file type 😛
ye
identify/extensions.py line 80
'ipynb': {'text', 'jupyter'},```
wait no, this is reversed
ugh i don't wanna set up a dev env but I wanna commit that
identify/extensions.py lines 147 to 148
'py': {'text', 'python'},
'pyi': {'text', 'pyi'},```
:p
😔
It should work then, maybe their identify is super old?
!pypi pre-commit
2.15.0...
pre-commit version: 2.15.0
sys.version:
3.8.2 (default, Apr 8 2021, 23:19:18)
[Clang 12.0.5 (clang-1205.0.22.9)]
sys.executable: ...snip.../venv/bin/python
os.name: posix
sys.platform: darwin
hmmm
the error message does say Try upgrading identify and pre-commit?
butttt
how did you find that
the report states identify==1.4.14
sheesh
Hmm, what solutions do we have though? A note in the documentation makes sense, but I can't think of an actual technical safeguard. I don't believe you can configure the minimum identify needed.
To be fair, that is a fairly old identify version and the error message does say to try upgrading it.
yeah
I'll comment on the issue if you haven't already :)
Marco already did!
i very much appreciate all of the information they gave us
ah
I wanted to thank them for the amount of information that they provided lmao
most issues are not that informative
perhaps it was fixed at some point, but since their version is so old that was still not a feature 😛
oh lmao in retrospect if this wasn't working on modern version then all pre-commit versions would have been bugged
3 files changed, 109 insertions(+), 201 deletions(-) -- not the worse but the clean up did feel a bit sketchy ...
It's more that I'm worried I accidentally screwed up a test by rewriting it. The problem is that there's two interfaces regarding file collection and discovery, there's get_sources and gen_python_files, they're very similar but not quite the same. I've gotten away with using the same convenience function for some of the gen_python_files ones (even though it was designed for get_sources) but anything related to .gitignore is unsupported :/
ah
what's the diff size?
is the commit history clean and readable or kinda a mess?
here's another one
like I'm sometimes OK reviewing a massive PR if the commit history is well split up into (hopefully atomic) and well described changes
Here's the commit histories, since idk enough to know if they are well split since I wrote them
https://github.com/discord-modmail/modmail/pull/69/commits
https://github.com/discord-modmail/modmail/pull/53/commits
Yeah it's not actually that bad, although the sheer diff size means I would straight up reject reviewing the PR
lmao
the diff size is because it adds an entire subsystem and docs for said system
at least for the first one
1k is pushing my limits and 2k+ is just too much logic to review at once (even over several sessions)
the second one is because it adds an entire other system as well
i think its closer to 1500 👀
rather than the 2.4k that it says
there's like 400 of docs, 200 of spaced out test cases using parameterize, and at least 200 in docstrings 
doesn't really change much
true
yeah they might be a little bit big
this is another one lmfao
i may have a problem.
tests/test_black.py | 887 +++++++++++++++++++-------------------------------
tests/test_format.py | 155 +++++++--
tests/util.py | 83 +++--
3 files changed, 510 insertions(+), 615 deletions(-)
this is what the test suite cleanup branch currently looks like compared to main
TLDR:
5919 additions = 2486 + 2101 + 1332
1239 deletions = 295 + 702 + 242
Whelp.
across all three pulls
hmmm brb i need to figure out a command to see what the size of the current codebase is
current code
there's 1832 lines of .py....
for reference, the current repo has around 12092 lines
so I'm increasing the size of it by nearly 50% with three prs
how do you get this?
git diff main --stat
is there a way to get black to output the formatted file to stdout without formatting the file in place? i don't want the diff either with --diff, i want the whole formatted file, much like calling prettier without any flags on a .js file
You'll have to pass the file via stdin to get that
cat file.py | black - -q should do
Lovely!
Thanks for the updates! Having target_version as an argument makes total sense to me as well 👍 I had a look at the code and it looks reasonable, although I don't know vim plugins.
Our changelog is currently at the release, so a new heading needs to be added to the top. So please add a new ## Unreleased heading and place the change under ### Integrations. I left one comment as well. Since we're short on vim wizards, I'm willing to take your word on this working just fine 😄
Can anyone explain what this room is ?
Never heard of black formatter before
have a look at the pinned messages!
Seems good to me now that Jelle got his edit in as well! So how bout a merge?
cool how in this doc they use Black-style function declarations: https://docs.google.com/document/d/11VkNk9N8whxS1SrBv2BNN1Csl5yeTlgG7WyLrCB5wgs/edit#heading=h.s6u1i3i5ct8r
Python Callable Syntax This doc aims to clarify various ideas for improved python callable syntax. See this typing-sig for more background. There are have two related but different goals for new syntax: have a readable alternative to Callable[[args], return] syntax have a more powerful syntax t...
probably the multi-line style
yah
the sad face ): being in separate line 🙃 which I'm guessing is something that wasn't that popular in Python before Black based on Łukasz's post:
https://lukasz.langa.pl/1d1a43c4-9c8a-4c5f-a366-7f22ce6a49fc/
Oh, I've taken that as granted :D
Just the logical conclusion of dedenting lists etc.
if you add type annotations you don't have a sad face any more 😄
yeah the sadface style with closing parens on a newline
ahem @glad pilot 😉
(I remember you use the plugin, so you may have a fun time reviewing this pr)
@bright glacier okay I'd like to recap my previous changes. A bunch of those changes are in the lock files.
poetry.lock | 1513
18 files changed, 2101 insertions(+), 702 deletions(-)
Yes, true, the error message does say to try upgrading identify, that'll fix it.
Possible workarounds:
- don't use
types_or, but instead something likefiles: (\.py|\.pyi|\.ipynb)$. This, however, would mean that non-extensioned Python files wouldn't be processed - do nothing, and hope that the error message and the existing issue are enough to get users to just upgrade their
identifyversion
Are you manually changing the lock files
no.
This looks fine to me but the only knowledge of CORS is the quick reading of the MDN documentation. I hope someone else with more web dev experience can pitch in.
LGTM
Is your feature request related to a problem? Please describe.
The cache files are not thread/process safe. I've checked multiple projects simultaneously in different processes but get permission errors when one process is writing to the cache while another is reading from it. On linux the fix is pretty easy: set a different temp directory for each process using the XDG_CACHE_HOME environment variable but there is no equivalent for Windows (there's somewhat an equivalent but you ne...
Describe the bug
"string".replace('"', '\"') it is transformed to "string".replace('"', '"')
To Reproduce
Self evident in the description. Needs no arguments, just run plain black on any file containing that line.
Expected behavior
Shouldn't change the replace sentence.
Environment (please complete the following information):
- Version:
main, Linux, Python 3.8.10, gcc 9.4.0
Does this bug also happen on main?
Yes
Additional context...
pretty sure it's not the first time somebody opened an issue about this
Quotes are the literal worst
I peeked into the implementation of shlex.quote recently and my brain exploded
Argument 2 to "assert_collected_files" has incompatible type "List[Path]"; expected "List[PathLike[Any]]" -- there has to be something really dumb I'm missing here but I do not know what that is 😦
Ugh, ignoring that I accidentally wrote a pretty dynamic piece of code ... mypy hates it
https://mypy-play.net/?mypy=latest&python=3.10&gist=e72d7fcd92ae88e0680187112a9245bc seems to work for me?
I worked around it, and anyway mypy hates all of my code
Sometimes wish I could just refine variable types and not have mypy complain a bunch. I get it's relatively unsafe but these asserts don't feel valuable
that's because List is invariant
Yeah I don't really get it still -- invariance and covariance are not terms I know
I mean, I still have 15+ errors, I don't think this code will work anyway
the summary is that if something needs a List[something], you must give it exactly that, not a List[something similar]
this is needed for safety when the list is mutated
often annotating arguments as Sequence or Iterable will help
That has confused me too 😅
and this really is one of the most frustrating parts of typing
I think what confuses me is how an explicit type annotations all of sudden makes it OK according to the doc
oh something with type context probably
it infers a different type for a list depending on context
I think I understand it
makes kinda sense?
So to put it simply, let's create one function that takes a list and adds a value: ```python
class A:
def init(self, value):
self.value = value
def add(container: List[A], value: str) -> None:
container.append(A(value))
Then we create a subclass called B: ```python
class B(A):
... # Whatever, it is different
If a list was covariant things would become troublesome
target: List[B] = [B('a'), B('b')]
add(target, 'c') # UH OH!
# target now contains [B('a'), B('b'), A('c')]
# changing its type to List[Union[A, B]]
Does that clarify it @bright glacier, @errant barn?
no, not really unfortunately
Well yes and no :D Because surely it is still a valid List[A] for all purposes
But I get that mypy would want to make the distinction
Yes exactly, but we typed target as List[B]
So without mutation into consideration it works, add() can do the same with List[A] as it can with List[B]. But if it adds an element, the type of target changes!
it's all honestly going over my head, it sounds legit but yeah no I'm too dense for this today
def assert_collected_files(
src: Sequence[Union[str, Path]],
expected: Sequence[Union[str, Path]],
*,
exclude: Optional[str] = None,
include: Optional[str] = None,
extend_exclude: Optional[str] = None,
force_exclude: Optional[str] = None,
stdin_filename: Optional[str] = None,
) -> None:
src = [str(Path(s)) for s in src]
expected = [Path(s) for s in expected]
if exclude is not None:
exclude = black.re_compile_maybe_verbose(exclude)
if include is not None:
include = black.re_compile_maybe_verbose(include)
else:
include = DEFAULT_INCLUDE
if extend_exclude is not None:
extend_exclude = black.re_compile_maybe_verbose(extend_exclude)
this code was a mistake -- I don't know why I didn't remember all of this redefinition would be problematic
As a comparison, change List to Tuple and it works because tuples can't be changed
nope, I just can't understand it
I get it's the mutation that's problematic now but that changes almost nothing for my understanding
Tl;Dr ```python
def add(container: List[A], item: str):
container.append(A(item))
target: List[B] = [B('a'), B('b')]
print(target) # [<main.B object at 0x000001D1CBB594F0>, <main.B object at 0x000001D1CBEE3DF0>]
add(target, 'c')
BAD! Types can no longer be statically trusted
print(target) # [<main.B object at 0x000001D1CBEE3BE0>, <main.B object at 0x000001D1CBEE37F0>, <main.A object at 0x000001D1CBB594F0>]
Oh yeah same, I don't get the difference between covariance vs. contravariance. I just understand that invariance means that only A can be used where A is accepted.
I guess to explain it in my own words:
- since add's container type annotation is List[A], that means it's allowed to modify it with items that A permits (assuming covariance)
- that's a problem since a caller could pass a list typed more strictly than List[A] and add could change it
- and it isn't an error on add's side because for all it knows
containeris List[A]
that's probably wrong though
that's right!
I always thought containers following typing.Sequence were also mutable, but apparently not?
typings.Mapping / collections.abc.Mapping isn't mutable
Then tuple wouldn't be a sequence 😔
So yeah, I always assumed the same thing but when you put it into words.. yeah
Let me make it a bit better, I don't really miss your old flower. The new one fits you quite nicely
Yesterday I wrote a stub if-else tree which I replaced with a simple regex today.
It's been a slow day and coming home and doing some refactor for only for mypy to hate my code (even if it's right) is not what I needed
I also wrote a feature a few weeks ago that's so bad I need to fully rewrite it.
does anyone have any good ideas on how to rewrite this code to not depend on implicit type narrowing + implicit type redefinition?
I could just add four asserts for include, *exclude* but I feel there could be something better
oh I forgot the link sigh: #black-formatter message
we could turn on mypy's --allow-redefinition flag, not sure if it works well with mypyc
or use new variables with a separatename
That's probably not a good idea
I'll do that, I don't like it much but it seems for the better
Oh right lol, I was about to do
if x is not None:
new_x = Whatever()
else:
new_x = None
IIRC this is invalid until recently (or the reversed form) when Sully did a PR
.. I should go look up the PR, I don't think my memory can be trusted today
python/mypy#11002
I can never remember their full nick or name so I just used a short nickname I've seen before
He goes by Sully in real life too
TIL
hmm
what is the difference?
I'm kinda interested in seeing if I can implement this if y'all think its useful for psf/black
That's what diff-shades is all about
I just haven't found the motivation to continue work on it
tldr since you have the repos and code and workflows already, it would just be adding the msg from the workflows somehow
Diff-shades is not ready for use yet, it's really fragile and non-user-friendly
ah
Woah, that's cool 👀
Indeed!
Also finally! mypy -p tests is now passing (well actually not, but for reason pytest's fixtures aren't being picked up properly by local mypy)
I honestly don't quite understand why running mypy via pre-commit resolves the pytest fixture errors but oh well I'm not in the mood to figure it out.
Wow, flake8 tests/ was a mistake 😅
what if you exclude fixtures
❯ mypy -p tests --pretty
tests/test_no_ipynb.py:25:48: error: Function "_pytest.tmpdir.tmpdir" is not valid as a type
def test_ipynb_diff_with_no_change_dir(tmpdir: tmpdir) -> None:
^
tests/test_no_ipynb.py:25:48: note: Perhaps you need "Callable[...]" or a callback protocol?
tests/test_no_ipynb.py:29:14: error: Unsupported left operand type for / (tmpdir?)
tmp_nb = tmpdir / "notebook.ipynb"
not sure what you mean by that
You definitely can, pytest just has its own meaning of fixtures
because some things aren't installed in the pre-commit venv
unless its a local hook but even then idk
I can't think right can't I today.
huh mypy does some cool stuff here to make this work
Describe the bug
Black does not correctly break lines in some cases. In the first two of these examples below it incorrectly puts foo( at the end of a line instead of breaking at the or binary operator as it should. In the other three cases, where I've added a third or clause, it breaks correctly.
This code
if (
foo(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
or foo(1, 2, 3, 4, 5, 6)
):
pass
is incorrectly formatted as
if foo(1, 2...
This release includes an important security fix
(https://github.com/aio-libs/aiohttp/security/advisories/GHSA-v6wp-4m6f-gcjg) and many
other improvements.
Description
The main goals of this PR include:
- improving consistency on how strict the test suite is -- Jelle has seen cases where a test did not fail to an incomplete test setup even though it should've
- simplifying tests for both ease of creation and reading via parametrization and helpers
- reorganizing the test suite by grouping more tests
- dropping test suite dependencies that aren't strictly necessary
The test suite could definitely do with more refactoring, but...
From https://github.com/psf/black/pull/2510
Run isort on some test files
@bright glacier just out of interest, why not add isort to pre-commit, so this won't need doing again?
To be honest I didn't want to ask the team if isort would be an welcome addition so I did it one time only for select files ^^
Could be cool in my opinion 😄
really? which case?
And despite the profile?
commented on it 👀
I see, thanks! I tend to use force_gridwrap, so all imports end up on their own line (so merge conflicts are minimised) and so had never come across that
ah, makes sense
i have a full ci on unused imports as well that it complains if they aren't used 😛
so its a simple matter of accepting both changes, and running pre-commit and then correcting the linting errors :)
on a related ci note, I've been looking into towncrier
!pypi towncrier
that's something to use for reducing merge conflicts
also no that's not related to black sorry
our grep powered news entry CI check has been working well enough for us so far ^^
ye, towncrier is a very different solution
changes instead get added to their own files
Yup I know.
👍
I actually have a grep news entry ci check too!
its nearly identical to black's
Its a good workflow, why would I not use it?
Can't say I went through each case line by line, but the changes and refactorings do make sense 👌 LGTM
I wonder if having test cases with multiple inputs and one expected result would be good. Like
a = long_call(
with_,
some=params,
)
## inputs
a = long_call(with_, some=params)
#
a = long_call(with_, some = params)
#
a = long_call(with_,
some=params)
or if just making a case for each would be better.
Usually such a scenario lends itself well to parametrization
^
BTW
there's not a way to see if a test raises a certain error with a paramertized test
!pypi pytest-raises
except if you use that :)
I meant that we would write those in the test scripts
Whereas now we have to provide an output for each input
Whereas? Yeah I'm going with whereas.
Are you talking about test_black or test_format?
formats, the tests that we write to the actual py files
I'm confused what you mean, felix
Now when we make formatting tests, we write something like
a = long_call(with_, some=params)
# output
a = long_call(
with_,
some=params,
)
So if we want to make many cases, the output has to be repeated every time. Which wouldn't have to be the case.
Since there (optimally 😅) is only 1 style, we could maybe shorten some tests a bit
am I making sense here 😄
I'm still confused on where the duplication of the output aka expected result is happening
a = long_call(with_, some=params)
a = long_call(with_, some = params)
a = long_call(with_,
some=params)
# output
a = long_call(
with_,
some=params,
)
a = long_call(
with_,
some=params,
)
a = long_call(
with_,
some=params,
)
Oh you mean combine tests?
Ye
Yeah my explanation wasn't very clear was it :D
Don't know how many cases of this there are though. Could be a non-issue
not too much, I'm not sure if what your example is are part of the test methods or are supposed to be run in the file itself
We could do that but the isolation and focused nature of the existing style is probably better
Since pytest is used as running, it first collects the tests, which means everything needs to be in a method, basically
I remember lots of tests being rather long and varied. So this probably won't fit other than the most basic tests
Isn't this what test_format SIMPLE_CASES is all about?
wait.
And FWIW I added assert_format and assert_collected_sources helper functions to simplify the more complex tests in that PR
So the simple cases assert only that the file doesn't change right?
I originally planned to add additional class of "semi-complex" tests similar to test_format.SIMPLE_CASES but that was painful to implement so I ditched that idea
Hope I'm reading it right
Well it depends on the data file used
If the data file doesn't contain a "# output" marker then any changes will fail the test
Yeah or that the output is the same
Yep, so not quite what I'm thinking about. But it's probably fine :D was just bouncing around ideas
Honestly I still don't really know what your idea is all about 😢
Say we test e.g. some line break thing
Like the long call I posted above
We could make multiple inputs that should produce a single output. Now we'd have to write the output for each input
Not as convenient for these longer scripts, I'll say that much. But for small snippets could be convenient
Oh, something like:
[case LineBreak]
[input 1]
x = func(
this=a
)
[input 2]
x = func(
this=a
)
[output]
x = func(this=a)
(i stole mypy's declarative test style)
I'm not sure, that would be a question for Jelle and not me
Oh ok 😄 but yeah that would be the idea. So the smallest unit tests would be easier
"unit" well anyway
It sounds reasonable, I'm not sure how many cases we could convert, but anyway we should probably do this at the data file level via a specific format (eg. mypy's)?
Yeah probably. It's just a generalisation of the current format after all
yeah, it's pretty basic right now, either you put an output marker or you don't
- https://github.com/python/mypy/blob/master/test-data/unit/check-basic.test
- https://github.com/python/mypy/blob/master/mypyc/test-data/analysis.test
here's some examples I was talking about
one thing I will note is that I don't like the lack of syntax highlighting due to the extension of the syntax instead via magic comments
Ye they do look nice
Oh I was just about to say the opposite, I hate how my linter marks every test file full red :D
double-edged sword for sure
🔥
I think I was able to fix the python_version markers in Pipfile.lock
The way I did it was really sketchy but hey- it works!

Description
This took way too much effort but in the end I was able to achieve a (mostly) functional Pipfile.lock ranging from 3.6 to 3.9 :tada:
Fixes #1645; fixes #2474, and probably fixes #1928.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary? -> n/a
- [x] Add / update tests if necessary? -> n/a
- [x] Add new / update outdated documentation? -> n/a
Huh
About that isort magic trailing command thing, I might be trying to implement it
i am trying to implement it :)
uh, maybe not
Yeah
Tested on 3.6, 3.7, and 3.9. Everything checks out!
why do we have flake8 B950 enabled in the repo btw?
(that's the line too long error)
This endpoint implements the document formatting request from the language server protocol spec: https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocument_formatting
There are a few limitations to this implementation:
- it ignores all formatting options that are passed in
- on syntax error it returns a generic "internal server error" message
- it only supports
file://URIs - there's no support for initialization protocol messages: https://micr...
its kinda annoying that i had to url shorten some links because they're too long to fit on a single line (in a comment or docstring)
huh, TIL: https://github.com/apps/dco
I've included that note in all my commits for ages because my IDE just... does it, but is there any actual benefit to it?
would # noqa: B950 not solve this, if B950 comes from a flake8 plugin?
yeah probably, but then what's the point of that lint anyway? All code is formatted to make sure it's not violated anyway
Seems more like an attempt at a legal declaration? Dunno if it's effective or not 🙂
ah yeah, true that 😆
Ah, fair enough
black doesn't always respect line length limit
most notably, in (doc)strings and comments
I'm not sure about B950 since it's from bugbear but flake8's built-in line length error code ignores strings/comments with long URLs as long as that's all that is in that line
welp, looks like bugbear doesn't do that:
https://github.com/PyCQA/flake8-bugbear/issues/176
How can I place one newline before and after function instead of two using ~/.config/black.
I know this might not be the correct channel to ask this but anyone here who contributes to pandas official repository?
You can have a look at the CLI options: https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#command-line-options But no, that particular configuration is not available. Black's style is rather uncompromising.
I was about to say "none that I know of", but I see @stuck vapor in Pandas' list with a hefty number of contributions 🥳 How come?
I have just switched over to contributing to bigger projects like pandas and got two Doc issues assigned, solved one of them and needed help with second one. So thought if someone who already contributes to pandas can help me out.
I have joined there gitter channel as well
Oh 😅 yeah you're in the wrong place for that mate. The gitter channel sounds like a good idea 👌🏿 But welcome anyways! I'm glad you're expanding your contributing horizon
yeah , thank you for your time buddy🤝
Describe the bug
Black attempts to run with too many executed threads when running in a container (e.g. in kubernetes).
It is well understood that containers do not mask the number of physical cores available, despite the fact that the container itself might be limited by the amount of CPU it can use at one time. This means that using the result of os.cpu_count() to spin up that many threads can cause a huge number of threads to be created. The memory overhead of this can cau...
Description
Fixes Issue #2512. This does introduce a new CLI parameter but it fixes a pretty core issue. See the issue for more details.
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [ ] Add / update tests if necessary? -- Unsure if this needs testing.
- [x] Add new / update outdated documentation? -- I checked this and the
--helpis automatically inserted into the docs.
Regarding https://github.com/psf/black/issues/2505 , is the black pre-commit hook expected to run on non-extensioned Python files?
If not, seeing as there's no way to specify a minimum identify version in pre-commit, a solution could be to just use files instead of types_or
someone explained the solution here: https://github.com/psf/black/issues/2505#issuecomment-925341052
someone
😆
Yes, the potential issue is that there's no way to something like minimum_identify_version (like there is for minimum_pre_commit_version), so this just relies on people running pre-commit, having it fail, and upgrading based on the rather long traceback
If that's OK, then perhaps the issue can be closed?
Oh lmao that is you
Jeez, I referred you to your own comment.... I'm sorry, I'm not stack overflow, that's not what I should be doing 😛
Yeah, someone could probably close the issue even though the original poster never responded, it's not a bug
I'll have a look
psf/black#2505
Okay I don't really know what's in play here honestly 😅
So: someone is using our jupyter hook without installing the extra.
Original discussion there
Oh ty
Tldr the identify dependency of pre-commit is too low on the user's install
🤣 no worries
Essentially, the alternative would be:
files: (\.pyi?|\.ipynb)$
instead of
types_or: [python, pyi, jupyter]
Advantage:
- users don't get scary-looking tracebacks if their version of
identifyisn't recent enough
Drawbacks:
- if someone has a file with Python shebangs, but which doesn't end with
.py, then it won't get formatted
Given that the min version of identify is a year old, imo a user should have upgraded in over a year
It doesn't look like they're using the jupyter hook, I think this issue will be present even if they just use the regular hook, just because types_or: [jupyter appears later in .pre-commit-hooks.yml
Right, probably true
Also I'm not sure if I commented in it but that user was a great provider of what the problem was.
Sure, they may not have read the message at the bottom of the traceback which fold them to try upgrading identify, but they provided a lot of information
And honestly I think that's the solution
While yes, the tb is extremely long, I don't think black should make compromises for pre-commit failures
Yeah, top-quality bug report!
Doesn't seem like there's a way, and pre-commit folks don't seem to want a "minimum identify version" feature https://github.com/pre-commit/pre-commit/issues/1946
Yeah true, but if the config is invalid we could try to help them anyway by requiring a version
They do tell the user what to try doing, and I'm not sure if the traceback has changed since then, either.
pre-commit/pre-commit#1946 on mobile, wanna see title
The issue author had a good point about the type being right but with an incomplete listing = no error
Oh I'm dumb, the upgrade message is right there at the start of the issue 🤣 Yeah that's definitely the solution to this error, and if the p-c folks are against a config, then it will have to do
Also the maintainer is right, but also wrong imo, while yes, there is a message the traceback should not be so long lmfao
I haven't seen much but that's the longest tb I've seen in a bug report so far.
Cool, so no action required on this one - thanks for your discussion!
The alternative way of finding files would be fine as well, but I think I'll just close this for now
BTW is it somehow extra expected that with pre-commit you always use the latest version?
I mean of course with every library you try to, but
dunno, but at least there's a really clear minimum_pre_commit_version flag for that
Yeah odd that they wouldn't accept that for identify 😄 oh wel
wait
that traceback is handled in pre-commit
this is the end user part 😛
I presume they reran pre-commit in verbose mode
Hey guys, So I am having an issue with black v20.8b1 installed via poetry on python 3.7.6 on linux(Pop!_OS 21.04 to be exact), when I run the command in my project using 'poetry run black .' I just see 'Aborted!' with no error message. It seems to work fine if I run it with the '-S' flag. I tried installing the newest version of black, 21.9b0, with pip globally to test it out, and that version works fine, however this project is for my work and I am not able to just update to the newest version atm. Any thoughts?
Wow 😅 it failed without any additional information? Have you tried to run it any other way?
I.e. without poetry
Did you give it a file to format
Yeah, I installed v20.8b1 with pip globally, and I had the same issue there, however with v21.9b0 via pip globally it worked fine
Hm
probably the local folder as in the example command
Yeah, I usually give it the entire directory to my src, but I also tried just a single file and still same output
I don't think the "Aborted!" message comes from Black itself, so it must be some other layer that's doing it
there's no other output than "Aborted!"?
poetry run --verbose black .? :D
Nope, just "Aborted!" and nothing else, happens with every flag except "--diff" and "-S"
And diff didn't need S?
Gives me the log of all the files it ignores based on my .gitignore, but still ends with "Aborted!"
Nope, just the diff by itself went through
Have you tried an isolated env with Black only?
I'll give that a shot, but my hopes are not high considering having it installed globally with pip had the same outputs
It'll at least give a clue whether a clean install is ok. I'm guessing your global packages have lots of other packages
"Aborted!" sometimes happens if the OS kills the process
Like the OOM killer on Linux
A new poetry environment with only black v20.8b1 installed gives the same "Aborted!" output
Damn. I don't know where to continue. Is the upgrade stuck on style changes or what?
For your team I mean
A new poetry environment may copy the site packages from where it was created
surely not by default 
This doesn't effect my whole team, as far as I know it is just my local environment. VSCode successfully auto formats on save with black, just a tedious issue I would have to work around seeing as our "make test" target includes formatting and linting before actually running the tests, was just seeing if anyone had seen this before and could help me fix it. If not then I can live with it
I meant that if the newer version works, is the reason for you not upgrading style issues or something else?
But yeah, at least I've never heard of something like this :/
I'd just have to talk to the team before upgrading it, wanted to see if I could fix the issue locally before moving to that option, tbh, we are due for some package updates haha
What OS are you on? If Linux I'd check /var/log/syslog to see if anything is getting terminated by the OS
Looks like nothing related to my issue gets logged
I appreciate the help everyone! Looks like I will just have to bite the bullet on this one and bring up a possible package update to my team. Again, thanks for the support!
As this approach was okayed in the linked issue, I think we can start polishing this.
I feel and agree this is the way to go as our main dislike for CLI args is around formatting changes.
I feel we could also use more click features to simplify the code + actually show how many workers the default detection would run in your environment in --help
But I won't block on requiring these changesif others disagree.
Heads up: issue 2513 is not linked to 2514
What do you mean?
Github issue auto linking: the body of pr 2514 said "Fixes Issue 2513", not "Fixes 2513"
So if the pr is successfully merged the issue will stay open
Just a small maintainer detail which could cause an issue that is actually solved to continue to be open :)
Usually I'll notice that the relevant issue wasn't closed during the merge, but it can't hurt to fix it before then -- thanks for noticing!
Looks great but there's a merge conflict on Pipfile.lock :(
Just letting you know that I love black!
So, I had a fragment like:
pbn_uczelnia.pbn_integracja = pbn_uczelnia.pbn_aktualizuj_na_biezaco = pbn_uczelnia.pbn_api_nie_wysylaj_prac_bez_pk = True
... and it got formatted to:
pbn_uczelnia.pbn_integracja = (
pbn_uczelnia.pbn_aktualizuj_na_biezaco
) = pbn_uczelnia.pbn_api_nie_wysylaj_prac_bez_pk = True
How could this be improved?
Well, perhaps I could get a warning on "enterprise-y" ...
GİT HUB
LGTM - If no one objects I'll merge later today.
LGTM as well, thanks for the updates!
Ye, imo it's not fun if I miss one of those issues and then I have a bug report issue that actually isn't a bug anymore, saves a little time 👍
Describe the bug
When running the function reformat_code (and code provided as a string) inside a Jupyter Notebook, it raises the following exception:
Traceback (most recent call last):
File "C:\Python37-32\lib\site-packages\black\__init__.py", line 585, in reformat_code
content=content, fast=fast, write_back=write_back, mode=mode
File "C:\Python37-32\lib\site-packages\black\__init__.py", line 843, in format_stdin_to_stdout
sys.stdout.buffer, encoding=en...
should this be fixed in black, or is it a bug in ipykernel? feels like the latter to me, but I don't know
if (mp<len(map)):
if (map[mp]==1):
IndexError: list index out of range
I think it would be cool for this project to take part in the global Hacktoberfest event. Hacktoberfest celebrates open source and encourages participation in the open source community.
More details can be found here: https://hacktoberfest.digitalocean.com/
I'm a bit hesitant to join in the event tbh, I haven't heard many positive things about it from other maintainers ...
you can assess PRs on case-by-case basis, there's no need to add the hacktoberfest topic
you can just label PRs with hacktoberfest-accepted if they're worthy (meaning, they're not a hindrance to you as a maintainer :P)
It was pretty good for typeshed. It might work less well for Black since it's a lot harder to make a useful drive-by contribution to Black than typeshed.
I'm pretty sure none of you guys would have an issue with labelling some PR if it was actually a good contribution if the contributor asked nicely and the contribution was useful
IMO, there's no need to advertise yourself as project taking part in Hacktoberfest
if someone wants to contribute, they already can
The event was a shitshow last year and i recommend not participating even tho it might drive away potential beneficial contributors
They stepped it up, you can report people now
policy here on pydis this year is that we're not globally enabling any of our repos but similar to what Jackenmen is suggesting opting in PRs that match (well, we're specifically opting in if the PR author asks, not adding it to our triage steps)
btw what is this
The real-time communication home of psf/black, a FOSS project all about building an uncompromising Python code formatter.
what is a "code formatter" tho
A tool that changes code to follow a certain visual style
https://black.vercel.app/ is a good online demo ^^
Playground for Black, the uncompromising Python code formatter.
I still don't understand what is going on there
It's programmatically editing your code to follow a specific style.
Why tho
OK, let's say we have this code:
if ( x == "hello, world!" ):
print ("hi!")
it's functional but pretty hard to read. Black will convert it into:
if x == "hello, world!":
print("hi!")
which is more readable and consistent
Say you have this:
def func(): print('hello')
```, black will make it look like this, which follows PEP 8 and is consistent:
```py
def func():
print("hello")
what is PEP 8
The official style guide for Python code within the cpython project ... although it's the most official unofficial style guide out there for all Python code
!pep 8 See the link below for the guide itself
I mean it's kinda cool but what are the practical parts? Is this just a fun project or is it being used for something inportant
It's often used to keep code style consistent through a huge codebase. The original creator made it for use at Facebook(?) I believe.
keeping code clean and easy to maintain can literally be a full time job, it's a nightmare to carry out in large teams. So tools like these come in super handy
How is performance of black measured? I have a patch which might be a performance improvement, but it's based on running rm -rf t; time XDG_CACHE_HOME=$PWD/t black . a few times - is there a better way to check?
perhaps blackbench from richard if its finished?
uhh, what's the type of performance win are we talking about?
just rewriting gen_python_files so it doesn't use recursion
ah that doesn't fall under blackbench's scope right now
can you not just timeit it?
Is that for me?
no for marco
indeed, no noticeable difference running %%timeit and some of the tests which use gen_python_files , and slight decrease for others - oh well, it was fun to try this anyway 😆
A 🎵
haha, yes lemon did make a song all about PEP 8
sheesh
Describe the bug
Non-idempotent source
To Reproduce
assert sort_by_dependency(
{
"1": {"2", "3"}, "2": {"2a", "2b"}, "3": {"3a", "3b"},
"2a": set(), "2b": set(), "3a": set(), "3b": set()
}
) == ["2a", "2b", "2", "3a", "3b", "3", "1"]
Run
black mytest.py
touch mytest.py
black --check mytest.py
Expected behavior
Second call to black shouldn't find changes to the code, but it does
**Environment (please complete ...
I love black the formatted!
.
Hey @bright glacier thought you were done with pipenv issues did you? 🤡
This may be my fault for trying to run in 3.10, but typed-ast 1.4.2 doesn't build. 1.4.3 does. All other dependencies are fine, so I'm not sure if this is a me thing, or if needs to be bumped
why >.<
It's just throwing pages of syntax errors from typed-ast
I can bundle it into a pastebin
the long term solution to this is to del typed-ast on py3.9+ but we first need to deprecate and remove python two support
lemme build 3.10 locally and test it out, but anyway I wouldn't mind bumping typed-ast
Is there a reason it was locked to 1.4.2 specifically?
yeah, there's a lot of issues on the tracker about this
Yup, I just confirmed typed-ast 1.4.2 can't build on 3.10. I'll submit a PR eventually
Thanks for noticing
Description
typed-ast 1.4.2 is broken on 3.10: https://paste.pythondiscord.com/etuheguzal.lua
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [x] Add / update tests if necessary? -> n/a
- [x] Add new / update outdated documentation? -> n/a
872bb94 Bump typed-ast minimum to 1.4.3 for 3.10 compat... - ichard26
excellent paste link
although @bright glacier they do expire three weeks after the last view. Probably not relevant for that issue, but that may be something to keep in mind.
weeks or months lol
think it is week? ||@delicate marsh||
!remind 2m click the above link
Your reminder will arrive on <t:1638695149:F>!
scrapers hit the site enough that most pastes get a bump lol
Haha
Describe the bug
When pipenv tries to lock dependencies, the following sub-dependency error arises:
✘ Locking Failed!
[ResolutionFailure]: File "/home/ru/.local/lib/python3.9/site-packages/pipenv/resolver.py", line 741, in _main
[ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev)
[ResolutionFailure]: File "/home/ru/.local/lib/python3.9/site-packages/pipenv/resolver.py", line 702, in resolve_packages
[Resolu...
Description
Python 3.10 having been officially released and available for setup-python, we can run the different CI jobs against it rather than 3.10-dev.
Checklist - did you ...
- [ ] ~Add a CHANGELOG entry if necessary?~ Not applicable
- [ ] ~Add / update tests if necessary?~ Not applicable
- [ ] ~Add new / update outdat...
!remind 2m click the above link
Your reminder will arrive on <t:1638759859:F>!
Arl wth did you start lol
Sorry for taking so long! I'm pretty convinced that this is indeed doing the right thing now 👍 I'm still a bit hesitant to give you the go-ahead because of my ongoing lack of knowledge about the visitor code, but the logic seems simple enough and I trust the tests!
A small adjustment though: please move the changelog entry to the latest heading.
Is your feature request related to a problem? Please describe.
Black normally removes all parentheses in some simple cases like:
if ((x and y)):
pass
is turned into
if x and y:
pass
But in more complex situations it does nothing, which is understandable.
However, one thing that I'd like to see is at least replace all double/triple parenthesized parts with a single parentheses. Currently this doesn't happen.
if not (...
What's a last version can I get in windows 7 32bit
Python 3.9, which I think means you should have access to the latest black version
But windows 7 has been EOLed for nearly two years now, and I don't think I've seen a 32bit machine that wasn't a microcontroller, or dedicated for something in my lifetime
Yup first 64bit was made in 2003, the year I was born lmao
I'm working on deprecating Black's Python two support wholesale, but I don't know how to actually emit the deprecation warning.
My first thought was to issue a DeprecationWarning but that's pretty ugly in the output (and is hidden by default)
But if we only emit a warning to STDERR people using black as a library won't be able to rely on any Python-level warning capturing systems they have in place (as a responsible developer) eg. pytest's
Thoughts?
What does pytest use black for
I meant like if anyone collects warnings while using black's unofficial API, example a test running under pytest
Ah ok
I don't mean pytest uses black, just that it collects warnings and presents them nicely which a stderr warning won't play nicely with AFAIK (i.e. nothing happens)
For the ugliness part, it would probably look fine without a traceback
But I'm not sure how you could address it being hidden
I don't think DeprecationWarning will give the majority of the people anything over stderr message
Cause usage of Black API or the -W error interpreter flag is rather unlikely even for all users of Black, yet alone people that format Python 2.x codebase.
but then again, issuing a warning is a single function call
What if you raise the warning instead of printing it
Honestly I think a stderr warning is fine.
I just think that if anything will be of use, it's the stderr message
ugh, I can't find where ubuntu stores screenshots
