#black-formatter

1 messages Β· Page 31 of 1

dense jungle
#

Actually we may want to keep an issue open for each preview feature long term to track problems with it

tired shard
#

discussions would be a good fit for those, but yeah they aren't enabled on black repo yet

errant barn
#

that could be nice, would be more informal and not everyone is on discord

tired shard
#

yep πŸ‘

tired shard
#

hmm yeah, didn't see that πŸ‘

tired shard
# flat kraken

psf/black#2193 could be closed on a similar reason but I think cooper would like a fix for this when they move it to their ownership, so not sure if it is worth closing

errant barn
#

I'll at least ref it

tired shard
#

yeah we can ref close it.

#

Also, we could close psf/black#1411, for the same reason that pipenv was removed, poetry lock files

toxic stormBOT
errant barn
#

I'd be down, quick poll?

tired shard
#

And, I am not sure if it is worth keeping psf/black#1544, when we already have a "main" issue regarding black API

toxic stormBOT
errant barn
#

Nice

errant barn
#

can we get to 300 lemon_hyperpleased

dense jungle
tired shard
dense jungle
dense jungle
errant barn
#

fine by me!

dense jungle
bright glacier
#

my gosh

#

y'all are having a closing party without me lemon_angrysad

errant barn
#

HYPE TRAIN

tired shard
bright glacier
#

could be worth documenting

#

I'll repurpose it for documentation

tired shard
#

umm yeah, could be a quick documentation pr

tired shard
tired shard
#

300 πŸ‘€

dense jungle
#

200 here we come

bright glacier
#

I'm trying to catch up on all of the notifications but ... dammit Jelle

tired shard
#

lol

dense jungle
tired shard
#

920 possible duplicate of 1190

bright glacier
#

psf/black#920
psf/black#1190

tired shard
#

umm not actually

#

920 is a bit overall

bright glacier
#

yeah they're different, 920 has an assert string while 1190 does not

tired shard
#

2038 duplicate of 2316, 2038 could be included with 2316

#

psf/black#2316 psf/black#2038

dense jungle
#

oh lol I just found those too

bright glacier
#

I thought it was also invalid below 3.6 / 3.5 IIRC

errant barn
tired shard
#

733 and 2121 are related, maybe we could merge the two

#

not completely sure, just skimmed through the discussion

errant barn
#

oh right, my bad πŸ˜…

tired shard
bright glacier
#

Cool, I remember triaging that issue a long time ago so I was like, uhh python two isn't the whole story here πŸ˜…

dense jungle
#

The original example of #733 is more in the "where to split lines" theme, arguably a dupe of #236

tired shard
#

hmm but the 733's linebreak is part of 2121 atlest

errant barn
dense jungle
bright glacier
tired shard
#

the original example would actually be better with what the user proposed though πŸ€·β€β™‚οΈ

errant barn
#

right, but that's very specific

#

no spaces between items, only small ints, and a line that just fits

tired shard
#

yeah

errant barn
#

not really a good basis for a style change

bright glacier
#

Just to elaborate a bit more into why, this would introduce another way to tweak Black's style and that goes against the goals of the project. If there's a way to make this work without introducing another option, we could maybe discuss it further but we are also hesistant to rely on pre-existing formatting as it's unconsistent and unstable.
I tacked on this comment fwiw

tired shard
#

2194 could be closed since primer is moving away and we have diff-shades :D

bright glacier
tired shard
#

45 πŸ‘€

bright glacier
#

(I clicked the manual refresh button though πŸ˜„ )

tired shard
#

lovely

tired shard
#

:D i closed 4 issues

#

oh well, bed time for me, there are several super short issues, i could possibly try to fix them tomorrow

errant barn
#

enjoy the stable release when you wake up πŸ˜„ sleep tight!

bright glacier
#

we're releasing in hopefully in the next one or two hours (depending on much mypyc hates me)

tired shard
#

uh oh, good luck πŸ˜„

bright glacier
#

Honestly I might give up on trying to add diff-shades to the wheel building workflow.

dense jungle
#

is GitHub unstable for anyone else? getting a bunch of timeouts and failures while trying to comment

errant barn
#

had one white page today πŸ€”

lament crow
#

it is a bit unstable, yeah

#

I had a bit of trouble with milestoning and labelling issues and my GH bot ran into some 502s

flat krakenBOT
lament crow
#

is it time? πŸ‘€

dense jungle
#

it is time

bright glacier
#

well kinda, I still need to do a bunch of other work to get the mypyc wheels ready

lament crow
#

πŸŽ‰

bright glacier
lament crow
#

ah yes, GitHub's having issues

flat krakenBOT
dense jungle
bright glacier
#

I have no idea

errant barn
#

maybe if it was a double commit somehow, the second one would have the original as its base

lament crow
#

they are separate commits, I remember a time when a squashed PR made 3 commits on a repo I maintain lol

#

one time occurrence but yeah

#

I don't recall there being any performance degradation when that happened but perhaps I just didn't check

neon loom
#

Add the points

bright glacier
#

I don't have a HN account surprisingly

neon loom
#

I never use mine to be fair

flat krakenBOT
#

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

Currently, Black (even with --preview) won’t do anything to the following code

f'N is {things["N"]}'
f"N is {things['N']}"

Describe the solution you'd like

It would be nice to be able to format these two expressions in the same way.

Describe alternatives you've considered

The obvious question is which one to choose, but I think it’s clear that the latter is more natural considering B...

errant barn
#

like lightning

lament crow
#

it might be worth updating issue templates to accommodate for --preview flag

flat krakenBOT
#

Describe the style change

Black could have an opinion of the correct case for \N unicode escapes. For examples, formatting \N{ox} to \N{OX}.

Examples in the current Black style

# This is not nice. All oxen should look the same.
print("\N{ox}\N{OX}")

Desired style

# Now the oxen will be happier.
print("\N{OX}\N{OX}")

Upper-case is standard for these, I believe. (For example, in the [Python docs](https://docs.python.org/3/how...

bright glacier
#

oh I would've thought we covered this already

flat krakenBOT
#

this worked fine in previous versions but was broken with the most recently release

here's the calling code: https://github.com/asottile/blacken-docs/blob/fb39015204c88c8f4f7365d7b4ac049ea8cb6450/blacken_docs.py#L237-L241

Describe the bug

FileMode changed in a backward incompatible way in 22.1.0

To Reproduce

here is the minimal reproduction

python3 -c 'import black; black.FileMode([])'
$ python3 -c 'import black; black.FileMode([])'
Tr...
marsh geyser
#

Congrats on the stable release πŸŽ‰

tired shard
#

Congrats guys!

tired shard
#

cc @elder tusk, re your comment on the same issue

silent apex
#

Great job everyone!

tired shard
#

I am working on psf/black#2067 which changes the code, like doesn't produce equivalent code, so black raises an internal error, whats the best way to go about this?

tired shard
#

I could make it ignore string literals, but that would be a bit faulty as if the string actually changes, it won't detect them

errant barn
#

looks cool, but also looks like a pain to implement :D

#

oh maybe not

unique mulch
bright glacier
flat krakenBOT
brisk kiln
#

oh wow, i was just asking for help related to this regex problem I had. what is this?

#

re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)

are you going to stop this madness?

lament crow
tired shard
tired shard
#

not all of them

#

but some

#

eg "\x1B" and "\x1b"

lament crow
#

I don't observe it with simple assert_equivalent(r'"\x1B"', r'"\x1b"') either so I just wondered if it's definitely not happening earlier, weird

tired shard
#

i will push my changes, gimme a second

#

try running on that branch

#

black tests/data/format_unicode_escape_seq.py --verbose

lament crow
#

ah, so it's about incorrect handling of "fake" escapes

#

this is an actual issue

#

you're replacing raw text \x1B with \x1b which is certainly different

#

you should only lower the sequence if it's actually an escape sequence

tired shard
#

yeah, sorry wasn't clear earlier, they are escaped unicode sequences

#

hmm, isn't that what the issue says or I read it wrong pithink

lament crow
#

only the latter of these can be replaced

x = "\\x1B"
x = "\x1B"
tired shard
#

ah okay, i read the "Unicode escape sequences" as literally escaped unicodes

lament crow
#

you want to replace first and third example here

#

as those get treated by Python as characters with ASCII code 3F (which is ? character)

tired shard
#

yeah πŸ‘

flat krakenBOT
#

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

Since Black just made it as stable, it would be nice to be able to set the --required-version argument to something else other than a strict equality. For instance, something like 22 would encompass 22.1.0, 22.1.1, 22.2.0, etc.

Describe the solution you'd like

The solution would essentially be to modify this line to a more soft comparison:
https://github.com/psf/black/blob/d038a24ca200da9dacc1dcb05090c9e5b45b78...

flat krakenBOT
#

Currently, our config options are documented only in a collapsed-by-default text block in https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#command-line-options. This is not very discoverable and makes it hard to give more detailed documentation, such as examples.

Instead, we should have a docs page with a separate section for each option. We can start with the existing descriptions, and extend them as needed for options with more complicated behavior.

dense jungle
#

was this your first time merging a PR @errant barn ?

#

(in that case, congratulations!)

errant barn
#

I snuck in some equally no-brainer thing yesterday :D but thanks anyway!

dense jungle
#

@bright glacier I'm really tempted to merge the pypackages PR right now

dense jungle
#

oh no

bright glacier
#

I was slowed down by a quick local test to make sure me rushing the merge of this PR wouldn't backfire :P

bright glacier
silent apex
#

Woah woah woah

#

In one day, y'all closed 38 issues

#

that quite a lot

dense jungle
#

that's because they were all dupes πŸ˜„

bright glacier
#

sometimes social media is uhh... interesting lemon_sweat

errant barn
#

oh wow the original tweet is 1500 likes now

flat krakenBOT
#

I did this manually for the last few releases and I think it's going to be
helpful in the future too. Unfortunately this adds a little more work during
the release (sorry @cooperlees).

This change will also improve the merge conflict situation a bit, because
changes to different sections won't merge conflict.

For the last release, the sections were in a kind of random order. In the
template I put highlights and "Style" first because they're most important
to users, and alphabetized...

bright glacier
#

there's an already open issue about this Jelle

dense jungle
#

I failed

errant barn
errant barn
#

That sly son of a gun

dense jungle
#

lol I found this because I was trying to give an example where --target-version affects the formatting

errant barn
#

making duplicates just for closing ;)

dense jungle
#

but I don't know what other example I could give

bright glacier
errant barn
#

oh right, nice

#

:D

late dewBOT
#

Hey @modest citrus!

It looks like you tried to attach file type(s) that we do not allow (.diff, .log). 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.

dense jungle
#

oh this one works ```(black) jelle@mbpt-root black % black --line-length=5 --target-version=py33 -c 'f(a, *args)'
f(
a,
*args
)
(black) jelle@mbpt-root black % black --line-length=5 --target-version=py34 -c 'f(a, *args)'
f(
a,
*args
)

bright glacier
dense jungle
#

um ```(black) jelle@mbpt-root black % black --line-length=5 --target-version=py35 -c 'f(a, *args)'
f(
a,
*args,
)

modest citrus
#

Hello, I'm trying to run the tests on my machine but there is a single test that fails but seems to work on the CI. It's test_skip_magic_trailing_comma and here are the file and the output that don't match: https://pastebin.com/Y90dW9HL https://pastebin.com/GLdmdhCG

dense jungle
#

it's the behavior from before the last release

modest citrus
#

I did pip install -e .[d]

dense jungle
#

somehow the test is picking up an older version

modest citrus
#

I just tried to uninstall black completely, installed it again with pip install -e .[d], removed .tox and ran the tests again with tox -e py but it's still not working.

#

If I do print(black) in the test, it prints <module 'black' from '/home/fredy/dev/git/black/src/black/init.py'>

bright glacier
#

can you make sure your local repository is clean / matching upstream?

#

git status and maybe git diff upstream/main...HEAD

modest citrus
#

Yes, except the changes I made which pass the tests on Github, there are no other changes.

bright glacier
#

I have no idea then

#

perhaps the test suite is still sensitive to the current working directory (due to weird configuration behaviour) but I would have thought tox would make sure that wouldn't be the case

modest citrus
#

printed the names of the files during the test:
/home/fredy/dev/git/black/tests/data/expression.py
/home/fredy/dev/git/black/tests/data/expression_skip_magic_trailing_comma.diff

bright glacier
#

linking those files aren't particularly interesting

#

the diff (against the current diff and the expected diff) pytest should've showed would be more interesting

modest citrus
#

how do I get that?

bright glacier
#

in the pytest failing output

modest citrus
#

E AssertionError: '--- [51 chars]n@@ -1,8 +1,8 @@\n ...\n-'some_string'\n-b'[16109 chars]ER\n' != '--- [51 chars]n@@ -21,27 +21,27 @@\n Name1 or (Name2 and Nam[13889 chars]ER\n'
E Diff is 20031 characters long. Set self.maxDiff to None to see it. : Expected diff isn't equal to the actual. If you made changes to expression.py and this is an anticipated difference, overwrite tests/data/expression_skip_magic_trailing_comma.diff with /tmp/blk_ufz2wc4h.log

#

where is self.maxDiff ?

bright glacier
#

that's weird hu

#

it's an attribute that unittest test classes can have to turn on full diffs

#

but I've never used it so I could be wrong

#

it's weird that only this test is failing

modest citrus
bright glacier
#

I have no idea 🀷

modest citrus
#

RIP

lament crow
bright glacier
#

do you happen to have an user black configuration file that sets the line length to something higher than 88?

lament crow
#

like, as gh action params, env var or something

bright glacier
#

that's literally the last idea I have to check

bright glacier
#

what are you planning to use it for?

#

ghstats is the autogenerated one (using some ... hacky automation) pulling the site assets from ghstats-source

#

the issue data is auto updated in ichard26/ghstats though

modest citrus
bright glacier
#

LOL, we need to make the test suite isolated

modest citrus
#

Do you want me to make an issue or you'll do it?

bright glacier
#

You could make an issue but I plan on fixing it today anyway so it doesn't matter

late dewBOT
#
Yeah okay.

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

bright glacier
#

And sorry for the bad first contribution experience πŸ˜… never thought the test suite would be sensitive to this

#

thanks for being patient with me!

modest citrus
#

Haha no worry, we're at least improving the code base doing that.

magic sky
#

What is Black?

#

Like I ain't got a clue what it does

errant barn
#

Channel description's got ya covered!

#

tl;dr Python autoformatter

modest citrus
#

If you know autopep8 or yapf, it's basically the same thing but with simpler configuration and sane defaults.

magic sky
#

I know neither of thise

modest citrus
#

It formats your code in a standard way so that you don't have to care about formatting.

lament crow
#

I wanted to try it out quickly yesterday but there wasn't really an option for providing the repo to fetch data for so I stopped looking into it

bright glacier
#

Yeah it's very built for my usecase

#

it probably wouldn't be that hard to hook up the main logic to an action but getting the initial issue dataset would probably require a manual step

#

the download.py update command / nox refresh session are repo nonspecific but yeah you need to need to setup the initial data assets by hand in the current setup

lament crow
#

ah, so there is initial manual step

#

thought it's all generated by action since the beginning

bright glacier
#

I could make it where if the action doesn't detect a issue-data.json, it does an initial pull of all of the issue data, and then uses the download.py update command after that

lament crow
#

I don't want to force any work on you

#

so I was more wondering if you were perhaps already considering it

bright glacier
#

Alright. Honestly the main reason why I probably didn't consider making it configurable is that it isn't 100% accurate. If an issue is closed and reopened, that isn't recorded and wouldn't be shown in the open issue graph for example. This is fixable by using the events endpoint but this would be a significant increase in complexity.

#

It only takes into account the most recent open/close state and information.

modest citrus
#

gg wp

dense jungle
#

dang

bright glacier
#

I got a saved reply πŸ˜‰

#

I could never write that fast

modest citrus
# flat kraken

Yeah sorry, I never think to use that even though it's nice

bright glacier
#

Don't worry about it too much, it means I get an opportunity to earn an issue closure so maybe I'll beat Jelle haha πŸ˜„

#

there's some friendly competition going on here

#

(a little out of date tho, it updates everyday at 10AM EST)

modest citrus
#

lol

austere lava
#

I can't compete with you guys anymore

errant barn
#

I have a dream

flat krakenBOT
lament crow
#

if you guys have RTD access, you can enable PR builder in its settings

bright glacier
#

I could do that right now, not sure why I never did earlier

lament crow
#

it's been out of beta for like a year I think

#

maybe a bit less

dense jungle
#

why are the index files .rst instead of .md?

bright glacier
#

I don't remember honestly

#

It's probably worth switching fully to myst-parser but I've ignored that for literally months now

flat krakenBOT
bright glacier
#

And actually about the usage and configuration section, I might shift it around still in response to the issue hauntsninja opened

#

This is all from memory though, I should look into this soon and refresh my thoughts on this

dense jungle
#

we can use my PR for iterating on that πŸ™‚

bright glacier
#

I need to stop procrastinating on other responsibilities by spending my time here though :)

#

!remind 1D hey, did you finish your other stuff and can look into roadmapping documentation improvements?

late dewBOT
#
Yeah okay.

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

bright glacier
#

this remind command is great, sadly it seems to be partially broken as some reminders aren't being delivered 😦

flat krakenBOT
bright glacier
#

lolwat lint is failing πŸ‘€

#

Oh, prettier doesn't like *text* for some reason 🀷

dense jungle
#

yeah I needed to prettier it

#

just pushed

flat krakenBOT
late dewBOT
flat krakenBOT
#

Describe the style change

"Complex" comprehensions (for some measure of "complex") should always be treated as multiline expressions, analogous to long lists/dicts that won't fit on a single line. "Simple" comprehensions continue to be rendered as a single line.

I appreciate that "simple" and "complex" are handwave-y statements; but as a starting point for discussion, I'll assert a comprehension ceases to be "simple" if:

  • It has more than one attribute access in any single term ...
flat krakenBOT
#

Description

Black raises error when formatting code that includes specific combination of fmt: off and fmt: on commands. The bug occurs when fmt: off is before intended block and fmt: on inside intended block. Bug occurs only in multi-level indentation (see: examples below)

To Reproduce
Try to format file with the code:

for i in range(2):
    # fmt: off
    for j in range(2):
        # fmt: on
        pass

Note: similar code but with single-level o...

tired shard
#

felix on πŸ”₯ πŸ‘€

errant barn
#

turns out we still have loads of duplicates :D

#

btw, I noticed you deleted your comment on one of the issues

#

any particular reason?

tired shard
#

yeah, i thought i was wrong for a second so deleted it until i go verify myself (to not create confusion), and when i come back, you were too fast πŸ™ƒ

errant barn
#

alright np :D

tired shard
#

and I saw your comment on a = b == c, will look into it (i am agreeing with you there; we should respect user-inserted parentheses, since we are anyways just adding them for very few cases - most probably)

#

been 2 weeks, no one has replied on it yet, so think we could use simple nodes concept on this also

errant barn
#

prolly worth it to wait for at least some comments so the work isn't wasted if we end up rejecting it altogether πŸ˜…

tired shard
#

maybe, well for the original author, they didn't feel anything much to add when I asked them on discord

I saw the discussion go by but didn't feel like I had much to add

bright glacier
flat krakenBOT
#

Pylint inline comments on wrong line after wrapping long line.

Inline comments that trail a command continue to trail the command after black wraps a long line onto multiple lines. While seemingly consistent with the original form, this makes inline comments like #pylint: disable=invalid-name ineffective since they are not on the first line of the command. For example:

asdf = namedtuple('nameoftuplegoeshere', 'fieldsgohere andnoather andanother morehere') # pylint: disadble=inval...
flat krakenBOT
tired shard
# flat kraken

Seems a duplicate of the reflow of inline comments issue ok not really, special case of it ig

errant barn
#

on it :D

flat krakenBOT
#

Describe the bug

When running black with a self-built Python 3.10 I get a segfault.

To Reproduce

Can be reproduced in Docker:

#Dockerfile
FROM ubuntu:20.04

RUN sed -i '/deb-src/s/^# //' /etc/apt/sources.list
RUN apt-get update

ARG DEBIAN_FRONTEND=noninteractive 
ARG TZ=UTC

RUN apt-get build-dep -y python3

# https://devguide.python.org/setup/#install-dependencies
RUN apt-get install -y build-essential gdb lcov pkg-config \
      libbz2-dev li...
dense jungle
#

now the fun starts

errant barn
#

:o

bright glacier
#

oh no

#

hmm are C asserts enabled in production builds of CPython?

dense jungle
#

no, only debug builds I think

muted haven
flat krakenBOT
#

Hello,

If you landed here because you either got a segmentation fault or a type violation along the lines of "TypeError: set object expected; got SomeOtherType" you're in the right place. Firstly my apologies for the issues you're hitting! Secondly, these issues are (almost 100% likely to be) directly related to mypyc which we use to compile Black into fast C extensions starting with release 22.1.0. This means a temporary fix will be to install Black from ...

bright glacier
#

I suspect we'll be getting more issues so I filed this issue to serve as a central location for these reports

#

apparently changing find_project_root to return a tuple instead of a Path broke quite a few integrations

slow ibex
#

you can replace some set annotations to Iterable or Container, mypyc won't raise typeerror in this code

bright glacier
#

It's not about what to change it to, we are well aware, it's just that we don't want to change it unless there's good reason especially as a set makes more sense for target_versions anyway

#

surprisingly there's no question on stackoverflow in regards to black + mypyc yet

#

If I see one I might go and create a SO account

bright glacier
#

hopefully the distro redistributors of Black are having fun

#

I wonder if condaforge cares whether we ship C extension wheels

#

it could also be a good idea to finally push Black for inclusion in the OSSFuzz project

lusty niche
#

hi

bright glacier
#

hello!

flat krakenBOT
#

The changelog for v22.1.0 mention the new stability policy (yay!):

At long last, Black is no longer a beta product! This is the first non-beta release and the first release covered by our new stability policy.

But there isn't a link to the policy anywhere overt. I ended up going to the PR to see where it was added into the documentation. Would it be reasonable to add this link to the changelog...

narrow sand
flat krakenBOT
late dewBOT
sour jay
dense jungle
#

it's already pinned

flat krakenBOT
bright glacier
#

Uhhh I am not a fan having Black do network requests

#

also much better handled using something like pre-commit autoupdate or dependabot IMO

flat krakenBOT
#

Thank you for the PR!


Oh, by the way, you can use special keywords in the PR description so GitHub will automatically close an issue upon merge. You can read more here: https://docs.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword. This makes sure any issue that should be closed are in fact closed (and I won't have to go proactively hunt for such issues!), keeping our very chaotic issue tracker ev...

#

Describe the bug

The verbose would claim that the filesystem root was identified as the project root (this is correct) and the configuration file came from /pyproject.toml (this is false).

To Reproduce

bright glacier
#

I rewrote the github action so yeah, fun.

flat krakenBOT
flat krakenBOT
tired shard
# flat kraken

I was just gonna pr this, got this after fixing ichard's issue and was running the tests, smh

stuck vapor
#

This new power operator hugging is so nice, thank you so much!

flat krakenBOT
fervent geyser
#

what is the black formatter

#

a formatting tool?

#

could anyone share a brief intro?

errant barn
#

Yes, it is! The channel description has links

fervent geyser
#

Thansk Felix, I ll have a look right now

errant barn
#

Ask away if there's something you'd like to know afterwards!

flat krakenBOT
#
  • use Black directly: the commands an autocommand runs are Ex commands, so no
    execute or colon is necessary.
  • use an augroup (best practice) to prevent duplicate autocommands from
    hindering performance.

https://vi.stackexchange.com/questions/26699/how-to-format-files-on-save-using-black-with-neovim-and-coc/36663?noredirect=1#comment65844_36663

Checklist - did you ...

Does this need a CHANGELOG entry?

  • [ ] Add a CHANGELOG entry if necessary?
  • [ ] Add ...
bright glacier
# flat kraken

ugh, this poor person doesn't know we don't support colon fences because we use prettier for markdown

tired shard
#

πŸ‘€ Right after zsol's comment about keeping things civil, it went a bit off

errant barn
#

Yep :/

flat krakenBOT
modest citrus
#

Btw, how do you skip the changelog action?

runic laurel
#

I'd like to generate ASTs programmatically and print them via black, is there a function in black that takes raw ASTs?

errant barn
#

due to newlines and comments mostly

little parrot
#

You could use the ast function for converting to a str and then pass that to black couldn't you?

tired shard
#

!d ast.unparse

late dewBOT
#

ast.unparse(ast_obj)```
Unparse an [`ast.AST`](https://docs.python.org/3/library/ast.html#ast.AST "ast.AST") object and generate a string with code that would produce an equivalent [`ast.AST`](https://docs.python.org/3/library/ast.html#ast.AST "ast.AST") object if parsed back with [`ast.parse()`](https://docs.python.org/3/library/ast.html#ast.parse "ast.parse").

Warning

The produced code string will not necessarily be equal to the original code that generated the [`ast.AST`](https://docs.python.org/3/library/ast.html#ast.AST "ast.AST") object (without any compiler optimizations, such as constant tuples/frozensets).

Warning

Trying to unparse a highly complex expression would result with [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError").

New in version 3.9.
little parrot
#

That yeah

tired shard
bright glacier
#

No, not really

tired shard
#

any reasons or its just not brought up before?

bright glacier
#

I'd argue my segfault issue is better suited as a pinned issue IMO, because it's a bug and bugs are associated as issues

tired shard
#

umm yeah, I agree with that, scratch that part.

bright glacier
runic laurel
#

Thanks for the answer, ast.unparse it is

tired shard
#

ah alright, so will it be considered for the preview issues or they will remain as issues? because imo they are gonna be "threads" on individual issues/etc

bright glacier
#

I honestly don't know - I don't even really know what GH discussions should be used for

#

other than release discussions (which seems really nice) I blank

tired shard
#

most projects are using it as: "Issues for bugs and new features, Discussions for everything else"

bright glacier
#

I suppose that's fair

dense jungle
bright glacier
#

Hmm I wonder if it'd be better to just autoappend --config=EMPTY_CONFIG in BlackRunner

#

I felt it was unnecessary given the diff size of my initial PR but I forgot these other tests and it's not unreasonable we could drop the ball on this again

#

If we do go down this route, I might just copy and paste the CLIRunner I've been using in diff-shades's test suite since it has most of the logic already

tired shard
modest citrus
bright glacier
bright glacier
#

not saying your PR is bad, just that it's frustrating how much people rely on these

tired shard
#

Yeah, I was guessing that and tried a different way but its not really a good way where you basically have a if-else in your main cli function and then you call find user root and filesystem root to compare the config path, it was having un-necessary function calls and didn't really like that method

bright glacier
#

honestly the fix I had in mind was to just hardcode a check for config == user_config_path() printing "from user-level config" if they match

tired shard
#

so ended up with this

#

yeah that's was my first solution

bright glacier
#

I mean, all of the non-formatting code needs a cleanup imo

#

I mean all of it really, it's quite a mess

tired shard
#

yep for sure, i have a wip branch cleaning up __init__.py and having a separate cli file

tired shard
modest citrus
bright glacier
#

Because I forgot it existed

#

does it autoappend config=empty_config, because I feel like it does now you mention it

modest citrus
#

def invokeBlack(
args: List[str], exit_code: int = 0, ignore_config: bool = True
) -> None:
runner = BlackRunner()
if ignore_config:
args = ["--verbose", "--config", str(THIS_DIR / "empty.toml"), *args]
result = runner.invoke(black.main, args, catch_exceptions=False)
assert result.stdout_bytes is not None
assert result.stderr_bytes is not None
msg = (
f"Failed with args: {args}\n"
f"stdout: {result.stdout_bytes.decode()!r}\n"
f"stderr: {result.stderr_bytes.decode()!r}\n"
f"exception: {result.exception}"
)
assert result.exit_code == exit_code, msg

bright glacier
#

wait what, empty.toml still exists?

tired shard
tired shard
bright glacier
#

It's probably fine if you break more, I suspect any cleanup will break 'em even more until we define a proper stable API

bright glacier
tired shard
#

that's part of the --config pr

bright glacier
#

ah

tired shard
#

which is waiting for your review πŸ˜„

tired shard
bright glacier
#

Yeah sorry, I've been overall burnt out / in a rut so I haven't anything really

tired shard
#

yeah no worries, its fine :D

bright glacier
flat krakenBOT
#

Description

From #2798: I'd like to include a FAQ entry about our refusal for tab support, and a short statement about the accessibility issue. TL;DR: never gonna happen, but we describe an alternate path that a visually impaired developer might use for a better experience with the Python ecosystem.

But is it too out of scope?

Checklist - did you ...

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

your wording is always so fun Felix

errant barn
#

hopefully it offsets the negative atmosphere

bright glacier
#

By the way, I plan on switching out tox for nox, do we think it'll be helpful to include a session which creates a virtual environment named venv at the root of the project?

runic laurel
#

I suppose for my case, I need black.format_str, but I'm confused about mode?

bright glacier
#

yeah this is what happens when we don't have stable API, nothing was really designed for library use. πŸ˜… ... but anyway what's up?

bright glacier
errant barn
#

what's the tldr of nox vs tox? Do we have an issue with it I mean

bright glacier
#

hmm, I don't think we have an issue for nox haha

errant barn
#

I mean issue with using tox

#

problem

bright glacier
#

I find it easier to work with especially as the configuration file is simply just a Python file. It's also flexible that way given you can write any Python code

errant barn
#

ok so just general improvements

#

sounds interesting

bright glacier
#

also, it would mean I could run the test suite properly in the mypyc build workflow since nox allows you to opt-out of the virtual environment autoprovisioning

#

for some reason tox doesn't allow this

errant barn
#

autoprovisioning, meaning..?

plain atlas
#

generates a venv and sets it up automatically

errant barn
#

separation between the testenvs?

bright glacier
#

Yeah.

errant barn
#

right, mypyc needs a single one I presume

bright glacier
#

well no, the problem is that cibuildwheel auto installs the compiled version

#

although I say that and switching to nox wouldn't fix all of the issues with the workflow .. hmmm

errant barn
#

okay πŸ˜…

runic laurel
#

nvm, figured it out. Glitch within neovim in vscode in combination with jupyter. Jumbled the black doc

bright glacier
#

gosh, you're scaring me Felix, I wouldn't close design issues as duplicates so readily haha

#

I'm confident you're making the right call but man the details can be fine sometimes

errant barn
#

πŸ˜… I do err.

dense jungle
#

I feel like we have too many design issues, there's not going to be a lot of things we'll ever be likely to change

#

so leaving them open just leads to false hope

bright glacier
#

Is there a reason why we disable mypy's cache? I see that it was disabled in the first commit. Perhaps mypy's cache was more problematic back then ... if so it's probably better now, no?

errant barn
#

And false hope or not, I think I'd rather have a single issue that deals with a style aspect even if we have a couple of different cases, like boolean ops vs binary

bright glacier
dense jungle
bright glacier
#

why is PyPy MacOS so slow in CI, like it really shouldn't be 5 times as slow compared to CPython MacOS

#

if this is due to the JIT needing to warmup, well then, didn't know the penalty of shorter runs could be this bad

#

oh wait, it might be due to coverage which is probably in Python and not C under PyPy...

dense jungle
#

hm we could maybe skip coverage for pypy?

#

I also notice that job frequently being the slowest

tired shard
#

well it did catch a coverage dip on my config PR

dense jungle
#

the pypy job specifically?

bright glacier
#

we could just disable coverage on MacOS pypy since its coverage data is not reported (or we could go the other way and have all jobs upload their results)

#

Could not send GitHub build status report for black. Make sure you have the correct GitHub repository permissions and your GitHub account is connected to ReadtheDocs.
hmmmmmmmmmmmm do I need admin permissions as RTD setups a webhook?

dense jungle
#

there is an RTD webhook

bright glacier
#

well that's confusing

#

does the payload history show anything noteworthy or is that all 200s too?

dense jungle
#

all green for the last few days

bright glacier
#

hmm, I don't think RTD has public logs for the PR status check POST requests

#

You need to make sure that you have granted access to the Read the Docs OAuth App to your personal or organization GitHub account. Learn more about this in our GitHub permission troubleshooting section.
Ah, IIRC the psf organisation hasn't authorized RTD yet

dense jungle
#

we also still have webhooks for Appveyor and Travis, should probably delete those

bright glacier
#

IIRC I actually sent an authorization request for RTD to the psf admins but it was ignored..? I could probably just ping EE publicly on some Github issue

#

yeah I did from who knows when

dense jungle
bright glacier
#

Probably email which sounds unreliable

plain atlas
#

hey ichard

#

which lines of code in diff shades print the summary?

#

specifically the diff

late dewBOT
#

src/diff_shades/utils.py lines 27 to 40

def unified_diff(a: str, b: str, a_name: str, b_name: str) -> str:
    """Return a unified diff string between strings `​a`​ and `​b`​."""
    a_lines = a.splitlines(keepends=True)
    b_lines = b.splitlines(keepends=True)
    diff_lines = []
    for line in difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5):
        # Work around https://bugs.python.org/issue2142. See also:
        # https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html
        if line[-1] == "\n":
            diff_lines.append(line)
        else:
            diff_lines.append(line + "\n")
            diff_lines.append("\\ No newline at end of file\n")
    return "".join(diff_lines)```
plain atlas
#

wait

bright glacier
#

it's just a fancy wrapper over difflib

#

there's also color_diff too

plain atlas
late dewBOT
#

src/diff_shades/utils.py lines 56 to 69

def color_diff(contents: str) -> str:
    """Inject rich markup into a diff."""
    lines = escape(contents).split("\n")
    for i, line in enumerate(lines):
        if line.startswith("+++") or line.startswith("---"):
            line = "[bold]" + line + "[/]"
        elif line.startswith("@@"):
            line = "[cyan]" + line + "[/]"
        elif line.startswith("+"):
            line = "[green]" + line + "[/]"
        elif line.startswith("-"):
            line = "[red]" + line + "[/]"
        lines[i] = line
    return "\n".join(lines)```
plain atlas
#

hm

#

this gonna be tough

#

-d difflib.unified_diff

#

yknow what ill be in a different guild

#

okay so i need file a and file b, names, and possible date

#

cool

flat krakenBOT
#

Description

Towards #2238

It's nicer to work with especially as it uses a bog standard Python file
for configuration. Its output is cleaner and it doesn't hide any magic
too.

Also the mypy cache has been reenabled since it speeds up pre-commit
hooks significantly which makes life easier :)

Hopefully this makes the initial set up process relatively painfree.

Preview: https://black.readthedocs.io/en/hello-nox/contributing/the_basics.html

Checklist - did you ...

...

bright glacier
#

if any contributors want to try out the nox sessions above that'll be wonderful

#

although if that sounds like too much work, reading the updated contributing docs would be a nice start

#

I regret not asking first time contributors what they thought of the contributing docs earlier, would make this less of a shot in the dark :/

neon loom
bright glacier
#

why, do you not like tox? or just curious πŸ™‚

dense jungle
#

my experience with tox has mostly been waiting forever for it to make a new virtualenv

neon loom
#

It's power is setting up virtualenvs for different python versions. For speed we run CI now with a ready to go Python env, it setting up a seperate env is of little value there. To be honest tho I've never looked into see if you can set it to use the vevn github action creates. Was also on my list for my projects

neon loom
#

It's value use to be testing Python 2 vs Python 3 on the same box. That was handy.

bright glacier
neon loom
#

We don't do that anymore

bright glacier
#

sadly the test session doesn't support full reuse since our test suite runs twice over because of the jupyter optional feature

neon loom
neon loom
bright glacier
#

full reuse (-R) -> no reinstalls at all
partial reuse (-r) -> still runs the pip install commands but since it's using the cached virtualenv, pip is pretty fast

neon loom
tired shard
bright glacier
#

I should document the -r flag though since it's a big time saver

#

I'd love to drop the need to rerun the test suite twice but I have no idea how I'd do that short of monkeypatching all of the imports of ipython which no I'm not doing

neon loom
#

lol

bright glacier
tired shard
# flat kraken

nice, this makes it much easier to write the min-deps tester, no need for additional script

bright glacier
#

wait it does?

#

how does tox screw you over?

neon loom
#

tox is the pre-commit of test running ... haha

tired shard
#

it didn't screw up, you would just need to call a python file and then output that to stdin and then make pip install pipe that output

neon loom
#

@bright glacier I was blown away last week when pre-commit CI ran black over bandersnatch to fix a formatting error on the PR ... I was like what ??@!!! - That was pretty awesome.

#

I assume that's Mr Sottle's doing.

#

Your set() friend πŸ˜„

bright glacier
#

Wait what what's so magical about it, we've had it enabled for so long and I don't think we enabled pre-commit.ci to autopush

neon loom
#

I didn't know it would run the new black over the source code too

#

And include any changes in the PR

#

Thought that was nice

bright glacier
#

oh wow

neon loom
#

Let me get the PR to show you

bright glacier
#

I already found it, that's magical

neon loom
#

Yeah, took me by surprise.

bright glacier
#

makes sense given the PR is 100% automated anyway

neon loom
#

Yeah, just didn't know it had been done

flat krakenBOT
tired shard
# flat kraken

you would need to add a line about having nox installed

bright glacier
#

I did add such a line

bright glacier
# flat kraken

this got me scared that I somehow made even more typos

dense jungle
#

you did

tired shard
#

hmm, i would have probably missed it

plain atlas
bright glacier
plain atlas
#

nox is misspelled smh

tired shard
#

oh wow that's right in the first para, oops

bright glacier
#

Yeah, I could move it into a heading so it's more visible but that seems overkill?

tired shard
#

yeah its fine

bright glacier
#

I'm no first-time contributor though, I'm like the 2nd most active maintainer since the project's beginnings

#

according to commits*

plain atlas
#

i was about to say

dense jungle
#

oooo

#
    91  Jelle Zijlstra
    90  Richard Si
bright glacier
#

wait what, I thought I was second

dense jungle
#

sorry I may not have pulled

bright glacier
#

I guess some commits aren't being attributed properly

dense jungle
#

sorry this includes some unmerged commits

#

you're actually one ahead

bright glacier
#

hey at least I'm winning at something now

plain atlas
bright glacier
#

you're probably gonna stay #1 for closed issues forever though

plain atlas
#

the best reason to split something among several commits :3

tired shard
#

among several PRs*

bright glacier
#

or push to main directly .. or do rebase merges ducky_devil

#

I'm surprised I haven't tried to push to upstream main before yet

tired shard
#

or use too much of suggest changes lol

#

it isn't protected?

dense jungle
#

no

plain atlas
#

pretty sure it-- oh

#

that would be fun

#

and by fun i mean not at all

bright glacier
#

yeaaaaa when I first got the commit bit I actually configured the upstream push URL to be a dead URL because I was afraid of pushing to main accidentally πŸ˜„

plain atlas
#

yay i have a recursion error-- this might be the first time i don't want recursion πŸ₯²

bright glacier
dense jungle
bright glacier
#

ah.

dense jungle
#

these ones

bright glacier
#

I suppose you were checked out on that branch then, I assumed you were on main

tired shard
#

oh, i need to get my pretty terminal output PR to work with --no-color

bright glacier
#

IIRC that's not a flag black provides

tired shard
#

it is

bright glacier
#

oh, it is, how does it work with click.secho then?

tired shard
#

dunno about htat

bright glacier
#

lol it does nothing

tired shard
#

only with --diff

#

rn

bright glacier
#

Yeah, probably not the best UX ever though

late dewBOT
#
You're the boss!

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

plain atlas
#

.xkcd 1739 cya later

bright glacier
#

that was me when I first joined the project πŸ˜‰

#

now I just label issues I'm responsible for as enhancements :p /hj

plain atlas
#

smh noob

#

i label my issues as feature, breaking change, and p1

bright glacier
#

!remind 18H fix-up diff-shades post-stable release + try to include a caching improvement too

late dewBOT
#
Aye aye, cap'n!

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

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
tired shard
#

src/black/__init__.py:410:1: C901 'main' is too complex (19) uh oh

#

its not even edited..

bright glacier
#

have fun

tired shard
#

--no-verify :D

#

lets see if it fails in CI

tired shard
#

uh oh lint fails

#

why always my PRs

#

smh

bright glacier
#

lol, wulrus is 3.8+ smh

tired shard
#

yeah

#

i was like "even tests now :ohno:" for a second lol

#

i have no idea how i fix this

#

|| ducky_devil I could always ignore c901 in for main||

#

ok good success, this

late dewBOT
flat krakenBOT
#

Would be very useful to be able to lean on black to add a specified header string python source files.

I'm imagining specifying a string in black config and upon running the format operation it ensures this string is present at the beginning of all formatted source files.

There are plenty of editor based tools to do this, and its relatively easy to write a simple script for this but it would be nice to just ask the code formatter to take care of it when it runs in the pre-commit hook.

flat krakenBOT
#

<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. Or run Black on your machine:
    • create a new virtualenv (make sure it's the same Python version);
    • clone this repository;
    • run pip install -e .[d];
    • run `...
flat krakenBOT
#

Describe the bug

internal error

To Reproduce

class GameOverView:
    def handle_key_press(self, received: bytes) -> bool:
        # fmt: off
        if received in (DOWN_ARROW_KEY, b"S", b"s") and i+1  error: cannot format blackbug.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: /tmp/blk_0gcejoy4.log


here have diff

```diff
--...
flat krakenBOT
#

Describe the style change

Black should format docstring line length.

Examples in the current Black style

def my_func():
    """
    This is a really long docstring. This is a really long docstring. Th
is is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring.
    """
    pass

Desired style

def my_func():
    """
    This is a really long docstring. This...
bright glacier
#

given how much flak we get fixing up docstring indentation I'm wary of this

#

also might require more special-casing in the AST check

dense jungle
#

anyway, agree this would be risky to do

bright glacier
#

I thought it just stripped indentation but it's been a while since I last read the code

#

tbf I'm not sure how you'd do that with a single string cleanly so you're probably correct

dense jungle
late dewBOT
#

src/black/parsing.py line 184

def _normalize(lineend: str, value: str) -> str:```
lament crow
#

I certainly depend on Black not splitting lines in docstrings

#

I want to not depend on it at some point but it obviously would require code changes...

little parrot
#

You parse docstrings at runtime?

lament crow
#

sure do

woeful badge
#

Hello folks
Am new here and also to python

bright glacier
#

Hi! this isn't the right channel, this is for discussion on the python autoformatter project named black. you might have better luck in #python-discussion

woeful badge
#

Been reading the code main.oy on GitHub
But the defined functions were not closed Like I was taught all this while e.g
Def culprit()

At the end something like this
culprit ()

Or is it not necessary?

bright glacier
#

well yes functions need some sort of code as their body or else they're invalid but you can call functions by referencing them by name and adding parenthesizes

woeful badge
#

Okay πŸ‘

flat krakenBOT
flat krakenBOT
#

Describe the bug

If we build the Python interpreter using AddressSanitizer then the interpreter segfaults when it runs black:

$ black --version
Objects/typeobject.c:5413: PyType_Ready: Assertion "type->tp_call != ((void*)0)" failed
Enable tracemalloc to get the memory block allocation traceback

object address  : 0x10fd45ba0
object refcount : 1
object type     : 0x10500b320
object type name: type
object repr     : AddressSanitizer:DEADLYSIGNAL
=======================...
flat krakenBOT
#

Confirmed that this happens on the latest version and in the playground.

Describe the bug

I don't know. I can't understand what your logs are saying.

To Reproduce

Run black on my file.

For example, take this code:

I can't post this on a public repo, but I'll email it to you privately if someone is going to take a look at it.

  • Black's version: 22.1.0
  • OS and Python version: MacOS version 11.6.3, python version 3.9.1
scenic parrot
#

Hello

#

Im new to open source and have no clue where to begin

#

Can someone please help me out

unique mulch
#

No idea if this is correct

#

Wanted to format files on save in VS Code

#

If I didn't specify then VS Code's trying to format on save with black installed in the venv

#

Which it isn't installed in

#

It is installed globally though

unique mulch
tired shard
green mulch
stuck vapor
little parrot
#

"Speaker: Łukasz Langa

What good is a code style if it's not internally consistent? What good is a linter when it slows you down? What if you could out-source your worries about code formatting, adopt a consistent style, and make your team faster all at the same time?

Come hear about Black: a new code style and a tool that allows you to format...

β–Ά Play video
delicate plaza
#

Hey I am a bit new to python programming and I am good in java so can any one guide me towards contributing in python language contribution (And I wanna contribute in native python development rather any other project)
I wanna build my portfolio in python

night trellis
#

What languages does black support?

#

Is it just Python?

mint barn
#

py

mint barn
bright glacier
#

Although Black does support formatting python cells in jupyter notebooks

flat krakenBOT
#

I think the way black uses click, parses the pyproject.toml, and extracts information from it are all done more or less perfect.
Therefore, I just wanted to copy some files verbatim to some of my projects, as blacks license allows that. Of course, here and there, some things I might need to adapt, but the basics would help a lot to avoid duplicate work.

However, I somehow, dislike to copy the...

bright glacier
#

I'm sorry but this is off-topic here.

neon loom
#

Wow, lots off off topic spam in this discord …

flat krakenBOT
ionic nymph
elder tusk
ionic nymph
flat krakenBOT
#

Describe the bug

Black 21.12b0 crashes with the

Cannot parse: 104:68:                 case {'aggregations': {'test_agg': {'composite': {} as agg_def}}} if ('after' not in agg_def):

message on the code provided below

To Reproduce

Use the following code


def _mock_search_fn(es_query):
    out = None
    match es_query:
        case {'aggregations': {'test_agg': {'composite': {} as agg_def}}} if ('after' not in agg_def):
            # First agg ...
flat krakenBOT
flat krakenBOT
#

<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. Or run Black on your machine:
    • create a new virtualenv (make sure it's the same Python version);
    • clone this repository;
    • run pip install -e .[d];
    • run `...
little parrot
#

hows this not raising a SyntaxError when checking the ast?

#

oh it still fails even with the removed duplicate argument

#

oh this is a line length issue lol

plain atlas
dense jungle
nocturne cradle
#

Not sure if this is the correct channel to ask in but can I do anything about black removing newlines in doc strings? It completely breaks my docs. An example of this would be this:

        """
        Makes a request to the api to get the tweets.

        Parameters
        ----------
        tweet_ids: :class:`str` ids of the tweet you're trying to fetch.

        Returns
        -------
        :class:`dict`
        """

Would get formatted to this:

        """
        Makes a request to the api to get tweets.
        Parameters
        ----------
        tweet_ids: :class:`str` ids of the tweet you're trying to fetch.
        Returns
        -------
        :class:`dict`
        """
dense jungle
plain atlas
#

what version of black and the args?

bright glacier
#

probably 21.12b0 or 22.1.0

plain atlas
#

aight lemme update black and try it on a project

#

woah pip got an update

bright glacier
#

yes it uses rich now, it's beautiful

plain atlas
#

furthermore the --preview flag was removed in the stable release? why?

plain atlas
bright glacier
#

try black --version

plain atlas
#

oh uh wrong version

bright glacier
#

lol

#

also not compiled so clearly your pip install is targetting a different python environment

#

(since the install log you shown had a manylinux wheel being downloaded)

plain atlas
#

smh

plain atlas
#

& i believe its that installed one from the install log

plain atlas
bright glacier
#

I was referencing how the wrong black you were using was also not compiled hence I knew you messed up the python environment

lament crow
#

did 21.12 ship with wheels?

dense jungle
bright glacier
#

A Pure Python one but no C extension wheels if that's what you're talking about

lament crow
#

ye sorry, meant mypyc-compiled πŸ˜„

plain atlas
#

not really a fan of this change, honestly

- cls.DEFAULT_VALUE = -1 + (2 ** max_bits)
+ cls.DEFAULT_VALUE = -1 + (2**max_bits)
bright glacier
#

No, probably since I didn't confident enough to ship 'em by default. I still wasn't super duper confident for 22.1.0 but I had some data which all came back stable so ehhhh

#

Other than a C assertion being violated it's been fine so far surprisingly

plain atlas
#
 async def converter(interaction, number: float) -> float:
-    return number ** 0.5
+    return number**0.5
#

πŸ₯΄

bright glacier
#

speaking about that ... I need to fix the comment handling regression caused by this PR

lament crow
#

I'm not used to this but I agree with the reasoning behind it and if I weren't used to how Black used to do this, it wouldn't strike me as odd

bright glacier
#

In hindsight I could've implemented Łukasz's wish for single operator expressions to be not hugged but at that point that's a lot of complexity for an exception

#

by then I already wrote a lot of magicial token handling code πŸ˜…

plain atlas
little parrot
#

surely its not good to have lots of exceptions to formatting?

bright glacier
#

yeah tell that to the python mathematics community though who was vocal against power ops being spaced

#

but yes I do agree we should try to keep exceptions at a minimum

little parrot
#

i also agree this was a good change (i had a lot of powers in my epq and it was really hard to read even with brackets)

plain atlas
late dewBOT
#

setup.py line 33

description="A concrete syntax tree with AST-like properties for Python 3.5, 3.6, 3.7 and 3.8 programs.",```
plain atlas
#

i think you've worked on it so i wanted to ask you :3

dense jungle
plain atlas
#

tbh i'm actually surprised you haven't worked on it

mint barn
#

is there a reason on why black formats doc strings and removes extra lines/empty lines?

dense jungle
#

I believe we only fix indentation and trailing whitespace

mint barn
little parrot
#

how are you invoking black?

mint barn
little parrot
#

my guess is this is just something vsc is doing for you

mint barn
#

mhmm i think so

#

it always happens and i thought it was black because after i do it, it always ends up like that

tired shard
#

and a --check --diff

little parrot
#

maybe its something youve set up for on save?

tired shard
#

to see what black actually does

mint barn
#

ill have to check vsc thank you

bright glacier
#

I might to be able to make the power op hug code a lot simpler as I just realized some AST information is available to the transformers but I'll do that later when I'm not under tight deadlines

bright glacier
#

Hmm PyPy 3.7 is a bit of a curveball as its ast module doesn't support type comment tracking

#

Right now I'm checking whether PyPy 3.8 does support it (it should as CPython added the argument in 3.8) but that doesn't really change anything since I don't think we could just drop PyPy 3.7 support

#

yeah OK PyPy 3.8 does support it, that means any bug of this nature won't be caught on PyPy 3.7 but that seems fine enough

flat krakenBOT
#

Description

Otherwise they'd be deleted which was a regression in 22.1.0 (oops! my bad!). Also type comments are now tracked in the AST safety check on all compatible platforms to error out if this happens again.

Overall the line rewriting code has been rewritten to do "the right thing (tm)", I hope this fixes other potential bugs in the code (fwiw I got to drop the bugfix in blib2to3.pytree.Leaf.clone since now bracket metadata is properly copied over).

cc @henryiii

  • [x] Add...
bright glacier
#

turns out copying a line updating just the leaf prefixes is a lot more involved πŸ˜…

tired shard
#

isn't this a bugfix rather?

bright glacier
#

fair enough, I'll do that after diff-shades comments since I still haven't updated it to pass --preview

tired shard
#

so not sure if it should go through preview

bright glacier
#

that was my feeling too since this is a pretty bad bug but I won't object to enforcing our stability policy rigorously / strictly

tired shard
#

uhh i mean you would need to add --preview for 11 months (which would bring other changes aswell) or make a workaround for this which isn't something i would like to do

dense jungle
tired shard
#

not sure, haven't looked into the issue

#

just skimmed through the pr

#

it happens for line too long issues

bright glacier
#
❯ black test.py --check --diff --color
--- test.py    2022-02-08 03:38:21.056764 +0000
+++ test.py    2022-02-08 03:38:21.935604 +0000
@@ -1,3 +1,3 @@
 return np.divide(
-    where=view.long_aaaaaaaaaaaaaaaaaaaa**2 > view.sum_of_weights_squared,  # type: ignore
+    where=view.long_aaaaaaaaaaaaaaaaaaaa**2 > view.sum_of_weights_squared,
 )
bright glacier
#

so kinda yes Jelle? since barring this bug black would not reformat this code

tired shard
lament crow
#

The thing is that it makes part of the 'code' you wrote completely disappear. Kind of serious

#

It's just type comments but still

dense jungle
#

ok, I want to look into this some more but it looks like we should just bite the bullet and break the stability policy. we should document this as an exception

bright glacier
#

I love how I'm responsible for all of these 22.1.0 bugs / issues / regessions / however you want to look at it

tired shard
#

this isn't really breaking any formatting though

bright glacier
#

I was responsible for the APIs being more strict, the segfaults, and now this bug

#

.. sigh

tired shard
#

on the positive side you were responsible for so many improvements/features on black lemon_hyperpleased

bright glacier
#

yeah but it doesn't feel great to be the reason why we have to violate the stability policy right after we start enforcing it

tired shard
#

It doesn't really get a new formatting behaviour, just fixes a bug of removing comments from previous feature

#

and like jack said removing comments is kinda serious

bright glacier
#

I'm not fighting or arguing about this at 10:46 on a weekday fwiw since I still got work to do.

#

The PR is in draft mode now.

lament crow
# tired shard this isn't really breaking any formatting though

That's imo fair point, since this isn't about the way Black adds or removes meaningless whitespace or parentheses, it actually completely removes something from the code. You certainly wouldn't leave a fix under a --preview flag for a bug in Black that somehow changed the meaning of code (I'm obviously ignoring that this technically shouldn't be possible with AST checks in place) completely.

bright glacier
lament crow
#

Ouch

bright glacier
#

I don't know which sub-bugfix caused that but that's unfortunate since the old code had a bunch of landmines

#

I suspect some bracket tracking / depth related behaviour got changed hence the formatting change

lament crow
#

I got one toy provlem: if someone runs with --fast, their Black won't necessarily crash on AST inequality therefore making any fix of such crash a change in formatting :)

#

Obviously I'm not serious

plain atlas
bright glacier
#

I give up today

dense jungle
#

this thing can wait

bright glacier
#

Mhmm.

dense jungle
#

huh did those changes in the diff-shades report happen because those lines have **kw in them?

bright glacier
#

It might actually be better to rewrite the power op code entirely to be more robust given how many landmines this approach seems to have.

#

Or actually I do remember how I only fixed the issue itself, but that does mean the code will continue to be a bit buggy which seems like a decent tradeoff for not violating the stability policy too much

tired shard
flat krakenBOT
mint barn
#

Hi! I'm not sure this question belongs here, but the question popped up when I fell in the middle of the tabs vs spaces holy war. I would like to follow the guidelines that were set to uniformly represent and read code when working in a team. I was told I need to switch to spaces instead of tabs. Personally, I don't really mind, what I do mind tho is that no editor that I know of provides a way to navigate 4 spaces at a time with the arrow keys. Is there any way to configure this in let's say sublime text, vscode or vim?

lament crow
#

there's a setting called Sticky Tab Stops in VS Code

#

I don't think Sublime Text has such a setting.

#

I would think Vim has something like that or has a plugin for that kind of behaviour but I'm no vim expert so can't help you there.

lament crow
mint barn
lament crow
#

it should work in most if not all popular editors (not counting vim since it's completely different from most editors πŸ˜„)

late dewBOT
#

Hey @whole osprey!

It looks like you tried to attach file type(s) that we do not allow (.save_multipla). 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.

austere lava
lament crow
#

you could just install a plugin, I think?

#

okay, these things don't fill me with confidence lol

#

well, mostly the /usr/local/bin/black thing

#

lack of updates isn't a big issue if it works (though that's arguable with the path forced on you :P)

austere lava
#

idk, even figuring out how to install a plugin was a bit of a chore

#

I just want to edit the damn file

dense jungle
austere lava
#

I have flashbacks to 15 years ago when I wrote enterprise java

silent apex
#

Woah

#

Django is now formatted with black

bright glacier
#

it's a bit πŸ‘€ yeah

silent apex
#

Woah, it's a 150k line diff

red sedge
#

I'd have been tempted to do the quote change separately...

stark yoke
tired shard
flat krakenBOT
#

I've moved from Ubuntu 21.10 to 22.04 and Black stopped working then. The configuration is fallowing
OS: Ubuntu 22.04
Python: Anaconda with Python 3.8
vim version: 8.2.3582
Package manager: Vundle

I did the fallowing to solve the problem as advised in the previous issues (e.g. #2547):

Removed black from .vim/bundle
Removed black from .vim
Installed Black by PluginInstall
Installed Black by typing :Black

The effect is fallowing:

Please wait, one time set...
elder tusk
#

i think pylance's issues on the black repo have been fixed in the latest update. if you use pylance and your computer is unhappy i recommend updating!

flat krakenBOT
#

Describe the bug

For files with a #fmt:off blocks, black will still remove empty newlines in these otherwise-unformatted sections. This is kind of pedantic, but it defies expectations that black would change anything at all here.

To Reproduce

Given the source file (note especially the trailing newlines at the end):

something = [1,2,3]


# fmt:off
other = [1,2,3
        ]



# fmt:on
another = [1,2,3]



# fmt:off
last = [1,2,3
        ]


``...
storm wind
#

I apologize if this is off-topic, but my company is thinking about adapting black to format our codebase. Is there a tool or way to check if something has already been formatted? Right now we're just having everyone install it on their ide and format before they push.

silent apex
#

black <path> --check --diff should do it I think

flat krakenBOT
silent apex
storm wind
#

Okay, I'll let them know, thanks!

bright glacier
#

Mhmm, just be careful that the action version is currently independent of the version of black used

#

I want to change this but I just haven't yet.

#

Using pre-commit in CI would also be a good solution

storm wind
#

Is that something I can set up in github?

#

I'm not a dev ops guy, so setting up this sort of thing is new to me

bright glacier
#

well pre-commit goes a bit more than CI, it's a framework to configure a set of hooks that usually run before committing (hence the name pre-commit) although pre-commit run --all-files exists too

#

I was expecting you to be familiar with it, but if you're not the action will probably make more sense as that'd require way less work

storm wind
#

I love way less work, now we're speaking the same language

storm wind
#

Oooh, fantastic, thanks!

bright glacier
#
name: Lint

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: psf/black@stable
        with:
          src: "src"
          version: "22.1.0"

here's one example configuration

storm wind
#

Nice and straightforward. Very cool

bright glacier
#

people would disagree on the version front and I would agree πŸ˜…

storm wind
#

What do you mean?

lament crow
#

the nice thing about pre-commit is that it allows all of your team members to install it and have it check formatting before committing it locally if they want to

#

But they don't have to use if they don't want to

bright glacier
#

so psf/black@stable is just the version of the action code itself, the action will install the latest version of Black from PyPI by default

lament crow
#

Since CI would check for it anyway

storm wind
#

Gotcha

dense jungle
#

I'd strongly recommend your team members install an editor plugin that formats on save too

bright glacier
#

many many many people think pinning the action will also pin the version of Black used which is fair

storm wind
#

Ahhhh

storm wind
silent apex
#

is the versioning system that black uses CalVer?

bright glacier
#

I stole the configuration style from stuff like actions/setup-python but admittedly it's less confusing when the underlying project the action sets up is different

silent apex
#

okie dokie, ty

lament crow
#

Version guarantees are described in the docs too since that might be relevant

storm wind
#

What's CalVer? Is that different than semantic versioning?

dense jungle
storm wind
#

Ohhh

dense jungle
#

we had a release in January 2022 so it's called 22.1.0

storm wind
#

Got it

#

Handy

bright glacier
#

year.month.bugfix

#

pip does the same thing as us

storm wind
#

One month sprints sound lovely πŸ˜…

lament crow
#

It's not very standardized

#

Pip only does year

dense jungle
bright glacier
#

Ah right

lament crow
#

21.3 happens in October I think?

bright glacier
#

they have minor instead of month

dense jungle
#

we just have releases when we feel like it

bright glacier
#

although we try to keep the pace at one per month

lament crow
#

The bugfix part

bright glacier
#

yeah, see 21.5b0, 21.5b1, 21.5b2 for example

#

could also call it micro which might be a bit more accurate

dense jungle
#

I think it's not necessarily a bugfix

#

It's just numbered releases within a month

#

But usually if we have more than one release in a month it's because we messed up something

pliant oriole
#

I just Set my discord hosted on gh bot to automaticly format with black

lament crow
#

That makes me wonder if someone made a gh bot that auto formats code in issue comments with Black

#

Probably a dumb idea but I'm wondering if someone already thought of it and implemented it lol

bright glacier
#

I mean, you could literally take mainline black, merge psf/black#2721 and run that in a GHA workflow lol

toxic stormBOT
lament crow
#

I mean, I know you can do it, I'm more wondering if someone did lol

#

Also, I think there's an external thing for formatting code blocks in Markdown

#

Not that I remember a name of it

dense jungle
#

blacken-docs?

lament crow
#

Seems it's mentioned in the comments, mdformat

flat krakenBOT
#

<!--
Please make sure that the bug is not already fixed either in newer versions or the
current development version. To confirm this, you have three options:

  1. Update Black's version if a newer release exists: pip install -U black
  2. Use the online formatter at , which will use
    the latest main branch.
  3. Or run Black on your machine:
    • create a new virtualenv (make sure it's the same Python version);
    • clone this repository;
    • run pip install -e .[d];
    • run `...
void cairn
#

k