#black-formatter

1 messages · Page 4 of 1

dense jungle
#

this seems like a real bug

flat krakenBOT
mint barn
#

Hi, i hope i can get some help here. I'm a bit clueless right now. Our Black setup changed with the new release but because we don't want to deal with it now, we try to pin the version to the one we used all the time: v22.3.0 in this PR:
https://github.com/cryptoadvance/specter-desktop/pull/2121/files
But now the formatting seem to differ a lot with my local black installation and i can't explain that. Also the debugging doesn't seem to be helpful.
ANy hints what i can do? We're happy black user since more than a year.

GitHub

Pin the black version. There has been a new stable-release of black but we're currently resisting using that.

dense jungle
#

and yes this is highly confusing and we will change it

mint barn
# dense jungle and yes this is highly confusing and we will change it

Ok, but how can it differ if i haven't specified a specific version, neither in my pre-commit-config not in the github-action config?

$ cat .pre-commit-config.yaml 
repos:
-   repo: https://github.com/ambv/black
    rev: 22.3.0
    hooks:
    - id: black
      language_version: python3.10
$ black --version    
black, 22.3.0 (compiled: yes)
dense jungle
#

the action will use the latest version (23.1.0) by default

#

and your local config is using 22.3.0

mint barn
mint barn
dense jungle
#

yeah I think the original motivation was so that you could use the action to format with Black versions before the one that we released the action with

lament crow
dense jungle
#

from @bright glacier's comment seems like this might not be trivial, but I definitely think this is something we should fix soon

lament crow
#

I'll look into it today

dense jungle
#

thanks!

lament crow
#

Got me interested

flat krakenBOT
flat krakenBOT
#

Description

Resolves #3382

Needs an update to the documentation and an entry to CHANGES.md. I would like to first check with you if this change is acceptable though.

There are 2 things going on here:

  • addition of .git_archival.txt set with export-subst git attribute so that black can be installed from a git archive, see: https://github.com/pypa/setuptools_scm#git-archives
  • update to GH action changing it to use GH action version when the version argument is not specifi...
glossy oak
#

Any devs and/or cooperlees here ? https://github.com/psf/black/pull/3531#issuecomment-1414144301 got me thinking if i understand the comment correctly (context; im trying to help with github actions integration, my pull request async communications via pr comments is a bit "meh" 🙂 )

GitHub

Description
Adds 2 new outputs to github actions which would allow pipeline maintainer to do conditional steps based on actions black did. These variables include is_formatted which defaults to 0 ...

neon loom
#

@neon loom comes from time to time 🙂

#

Please always tag me as I don't read the channel a lot

#

What's confusing? (Thanks for taking the feedback tho)

bright glacier
#

Regardless of however this turns out, I think it's worth adding a guide to the docs about handling Black upgrades, mentioning pinning and --required-version, etc. etc.

#

I do wish --required-version worked nicely with pre-commit but of course it doesn't.

#

https://github.com/psf/black/issues/2493 yeah this makes --required-version rather unusable. It might be worth patching Black to only warn if version information is clearly unavailable because we're running under pre-commit).

bright glacier
#

Heh, my Black 23.1.0 blog post ranks pretty highly on Google!

#

I was curious to why I was getting so much traffic from Google since usually Google isn't a major source of traffic for these posts.

#

ah of course, my mypyc stuff is still the most popular

glossy oak
#

@neon loom so if i got it correctly, the "optimal" way now would be to write the json from black itself and then action just utilizes the json to report it to $GITHUB_OUTPUT ?

glossy oak
# glossy oak <@813813914181697566> so if i got it correctly, the "optimal" way now would be ...

thats at least how i understood your comment on the pr .. eg, if black would create a json report directly, that sort of functionality would also support possible other task runners besides github actions and then the action/main.yaml would just use the generated json .. If that is the case, im wondering a bit about maybe there should be a possibility to set the location where the json would go via command line arg ..

#

(and i btw, truely like this approach better)

glossy oak
#

@neon loom that said, if the user provides "version" for black, and the version is old enough to not support generating the json, that would cause some issues and worrying part regarding that is that action.yaml still would have reference to outputs but there would be none in case of older black ..

ivory quest
neon loom
neon loom
ivory quest
neon loom
#

I remember reading something. The detail was no where like Richard’s tho.

flat krakenBOT
#

Describe the bug

Trying to install black in a Docker container (alpine base image) causes an error.

To Reproduce

Create Dockerfile:

FROM alpine:latest
WORKDIR /build
RUN apk update && apk add --no-cache python3 py3-pip
RUN python3 -m pip install black

Try to build it:
docker build .

The resulting error is:

#7 1.868 Installing collected packages: mypy-extensions, tomli, platformdirs, pathspec, packaging, click, black
#7 1.931   ...
flat krakenBOT
flat krakenBOT
bright glacier
#

I got fed up with seeing T: design. Sometimes stepping from a project helps with perspective :)

bright glacier
unique remnant
#

I Hi everyone, I will like to contribute to open source project but need a mentor so as to guide me. I don't know where to start. There is so much information and most of the newbie friendly open source I find are from two years ago.
If someone have already done contributions to open source I will highly appreciate the guidance

Thanks

ivory quest
bright glacier
#

I might just make it configurable. I know @lament crow also wanted to use it for their own projects. I want to use it for mypyc anyway so it'd be good to remove all of the hardcoding for Black.

#

Currently all of the front-end and helper scripts assume Black.

#

or at least I'll make it a lot easier to bootstrap your own copy.

ivory quest
# unique remnant I Hi everyone, I will like to contribute to open source project but need a ment...

my suggestion would be to find the project you enjoy and look into open issues, join discord or other form of forum the project has (if they do) and start contributing. Contributions are both issue triage (testing older issues if they are still valid, pointing invalid issues as closing candidates to maintainers etc) and actually working on code and PRs. There is not much more philosophy to open source. Have fun at it!

ivory quest
#

(as if I didn't have too much work already lol)

bright glacier
#

I'll try to take a look later today. It's actually split between two repos right now which probably isn't particularly friendly.

bright glacier
ivory quest
ivory quest
bright glacier
#

meh, I'll just get started right now. I was going to try and fix one more mypyc bug but this seems to be harder than I previously thought 😅

bright glacier
#

gosh the python code involved here sucks

#
    def oldest(self) -> Issue:
        lowest = min(i for i in self._issues.keys())
        return self._issues[lowest]

    def newest(self) -> Issue:
        newest = max(i for i in self._issues.keys())
        return self._issues[newest]

wtf

unique remnant
#

@ivory quest thanks!

flat krakenBOT
drowsy sonnet
ivory quest
flat krakenBOT
#

Describe the bug

This issue is more a heads-up than a bug report.

Follow up of conversation at https://github.com/psf/black/pull/3385. Seems like the test suite does not emulate real-world CLI usage. The paths get mixed up somewhere. This may be hiding some bugs: while writing #3385 I wrote a test to detect a confirmed bug (#3384 ) but the test was not failing, so I had to write a test with some patches to emulate the target behavior.

More details

When trying to repr...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

Add unexpected space before colons in slice when compute start parameter, but omitting other parameters : see https://peps.python.org/pep-0008/#pet-peeves and specially this sentence:

However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted...

flat krakenBOT
#

Describe the bug

When a comment is placed above a one-liner expression that uses a conditional statement, and --preview mode is on, black changes the comment and one-liner into a parenthesized block, or moves the comment to the end of the expression. The former situation with parentheses happens when the expression is preceded by at least one newline. The latter happens if there is no newline above the comment/expression. Neither of those formatting changes is expected.

**To Repro...

flat krakenBOT
glossy oak
# green mulch O.o where is it?

almost makes me think that there's Story involved with code like that .. It could be a bad story but story never the less 😄

green mulch
#
def apply(self, func: Callable) -> Sequence[Issue]:
   return list(map(self._issues.get, func(self._issues)))

def oldest(self) -> Issue:
   return self.apply(min)[0]

def newest(self) -> Issue:
   return self.apply(max)[0]
flat krakenBOT
bright glacier
green mulch
#

👍

flat krakenBOT
#

Describe the style change

Presently black inserts a space between the "#" and "|" in [Quarto][] metadata comments like #| label: cell1.

Examples in the current Black style

Space is inserted between the hash and the pipe:

# | label: cell-no1
# | echo: false

Desired style

No space between the hash and the pipe, which breaks document metadata parsing:

#| label: cell-no1
#| echo: false

Additional context

Quarto is the new(...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

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

I have a script that reformats all of the code in my project. First it runs isort, then it runs black. Isort lets me specify the paths I want to ignore as globs, which means I can keep the paths looking like filesystem paths, not complicated regular expressions.

black currently only lets me exclude paths with regular expressions, which means I have to maintain two copies of the paths I want to ignore. While regular exp...

#

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

Currently the only mechanism for excluding files from black is with a regular expression. Non-trivial regular expressions are notoriously difficult to get right, and so it's not always clear which files black will actually be targeting.

Describe the solution you'd like

Isort has a --show-files flag, that just prints which files isort will operate on. Ideally black would have a similar flag.

**Describe alterna...

flat krakenBOT
flat krakenBOT
#

@ambv

black has decided to go rogue and started failing the black checks on github workflow see https://github.com/buildtesters/buildtest/actions/runs/4138692064/jobs/7155399872 it was working all of sudden now its failing but there is nothing to black from the code-base. I have the workflow file https://github.com/buildtesters/buildtest/blob/devel/.github/workflows/black.yml and it is using the @stable version

Just to prove it i am going to run black on my code-base and it got not...

flat krakenBOT
flat krakenBOT
#

Description

Resolves #2783

The issue was partially resolved by #2820, but only for cases where the inner class body ends with a definition (class or def) and is followed by another definition. This change enforces a blank line after any nested class with a body (other than just ...) in stubs, particularly those ending with or followed by an annotation for an attribute.

I had to make a slight change to EmptyLineTracker.previous_defs in order to not put a blank line after t...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

I'm not sure if lowercase is the better decision, so I'm filing this feedback for discussion.

Reasons to favor lowercase:

  1. repr() uses lowercases:

    >>> "\x1B"
    '\x1b'
    >>> "\u200B"
    '\u200b'
    >>> "\U0001F977"
    '\U0001f977'
    
  2. I sampled 500K files from our codebase, lowercase is bit more popular (the count below is the total number escape sequences in strings):

    \x escapes:

    • lowercase: 440K
    • uppercase: 351K
      ...
neon loom
#

Wow - TIL mypy 1.0

flat krakenBOT
#

(I initially wrote the issue as a bug report, hence the issue template, but it's probably closer to a feature request.)

Describe the ~bug~

Lines that are too long because of trailing comments are handled inconsistently depending on whether they start with a mypy type: ignore directive.

Specifically, lines where the comment begins with # type: ignore are left as they are, whereas other such lines are broken up over multiple lines, which includes lines that contain `# type: i...

flat krakenBOT
#

Dear Łukasz Langa,

This is for you, since you were the one with the brilliant idea to start this abnormal cell growth that is black. For casual readers and passers-by, please consider that I am 50% black, as my mother is African, so this is no racist talk.

Ford once said about a car he was selling "And you can have it in any colour you like, as long as you like black." I can see why the name, here.

Big organisations all have their own code style. We all heard that MIcrsoft's new de...

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 `...
drowsy sonnet
bright glacier
flat krakenBOT
flat krakenBOT
#

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

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

I accidentally had the following configuration in a project:

[tool.black]
extend-exclude = [
    "backendapp/migrations"
]

If i then run black . -vvv, it tells me e.g.

manage.py ignored: matches the --extend-exclude regular expression

which is really confusing because backendapp/migrations is neither a regex nor should it match manage.py.

The solution is extend-exclude = "backendapp/migrations", which i only realized when looking into other projec...

gritty totem
#

hello everyone! 👋 I've noticed that there is an increasing number of lint/format/build tools that get great performance wins by using Go or Rust under the hood -- esbuild, ruff, and rome come to mind here. I'm curious how you all have thought about using these languages or others for performance-critical code or if there's any ongoing work in this vein already.

Apologies in advance if this is asked a lot -- I did a Discord search in this channel but didn't see much relating to this.

mint barn
#

hey

dense jungle
gritty totem
bright glacier
#

We're lagging behind on regular maintenance of the project already. Maintainer time is extremely limited so even the rewrite of a small part of the project would likely stall and never see the light of day.

#

I also don't know Go or Rust. I know some C but I don't think any of us would want to rewrite Black into C 😅

cyan panther
#

Is there a way to have black format Protocol class definitions like they're stubbed pyi files?

ivory quest
bright glacier
#

"If it's not written in <compiled language>, it must be too slow!!"

ivory quest
#

yeah

#

I mean, we have slow parts, but mostly not caused by the language itself

silent apex
#

usually black is rather fast, and i can't imagine what would require it to be faster than it is now

bright glacier
#

people using it on save with somewhat big files in IDEs complain black's too slow

little parrot
#

black in C would certainly be a sight

bright glacier
#

there's a relatively easy optimization that we can do to improve formatting performance by 50%, but it means dealing with a lot of edge cases

#

may look into that eventually

ivory quest
little parrot
#

turning off --safe?

bright glacier
#

wait actually I might be wrong, but the forced second pass seems unideal

#

I just remembered that we probably cut the third pass in the safety check though so it shouldn't have affected performance much.

ivory quest
#

wait, so black does more than 2 passes?

bright glacier
#

Hmm, so format_str does two passes if changes are made, and then assert_stable will do one more pass. A long time ago we only did at most two passes.

ivory quest
#

it's always fascinating to learn how stuff like this works...

bright glacier
#

With Rust they claim it would be basically instantaneous.

bright glacier
dense jungle
ivory quest
#

people then: *computer does stuff* haha, it's thinking!
people now: why do I have to blink to see the result?!

bright glacier
late dewBOT
#

src/black/__init__.py lines 1079 to 1085

dst_contents = _format_str_once(src_contents, mode=mode)
# Forced second pass to work around optional trailing commas (becoming
# forced trailing commas on pass 2) interacting differently with optional
# parentheses.  Admittedly ugly.
if src_contents != dst_contents:
    return _format_str_once(dst_contents, mode=mode)
return dst_contents```
bright glacier
#

Seems like a mostly safe optimization though? Not sure how we'd implement it though without breaking API compat.

dense jungle
#

format_str calls it; in format_file_contents we call _format_str_internal

bright glacier
#

So format_file_contents calls _format_str_internal directly so it can decide whether to call assert_stable?

#

I guess since we never had safety or stability guarantees for format_str that's fine.

gritty totem
# silent apex out of curiosity, is there "performance-critical code" that you're thinking of i...

I was referring abstractly to hot code in Black, but I'm not deeply familiar with the project internals or where the hot code might be.

As for the context of my original question, I recognize there's a pretty wearisome crowd of drive-by commenters asking their favorite projects to "Rewrite it in Rust" [https://transitiontech.ca/random/RIIR] and I could have made it clearer that I was asking out of curiosity and interest in contributing to such efforts. I've maintained enough projects to know how frustrating drive-by comments suggesting massive work items can be, and I hope that my question wasn't taken in that spirit

neon loom
#

I believe a lot of libcst is a python parser in rust …

#

And is our likely successor once we stop flogging blib2to3

#

@austere lava would know more 🙂

marble basalt
#

<@&831776746206265384> 🤷‍♂️

civic bane
#

!mute 960981532309340180

late dewBOT
#

failmail :ok_hand: applied mute to @mint barn until <t:1676738298:f> (1 hour).

flat krakenBOT
#

Is this related to a problem? Please describe.
I am running the latest Github action and the latest PyPi black version.
I realize that the Github action can specify which black version to use, but I don't want to maintain that, too.
I would like to add to the logs which black version is responsible to checking my Python scripts.
How can I accomplish that?

Describe the solution you'd like

I tried executing something similar to black --version in a subsequent step but if...

stone bough
#

Hi guys, how to make black format tuple and list like this?

CLASSES = (
        'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
        'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign',
        'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
        'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
        'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
        'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
        'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork',
        'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
        'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
        'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv',
        'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
        'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
        'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner',
        'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet',
        'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile',
        'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain',
        'window-blind', 'window-other', 'wood')
#

Black makes long tuple one item per line.

tropic verge
#

Hi! I want to apply black formatting on my Python project, including build/ directory which is excluded by default. I tried using --exclude but then .gitignore is ignored and other bad things happen. Is there an elegant solution to my use case?

lament crow
lament crow
#

The default value of exclude can be found in black --help

#

I'd suggest specifying such options in a configuration file, not as cli arguments so that anyone working on the project gets them when they use Black

#

exclude is a regex btw

tropic verge
#

The suggested solution, to use --extend-exclude isn't a good fit for my problem, as I want to remove a value from the default exclusion list

bright glacier
#

Might be better to allow .gitignore to be configured using a flag. Not sure how common either of these use-cases are though.

tropic verge
#

thanks @bright glacier, I can't say how common it is, but I can say that if you happen to have a build directory that you would want to apply Black on, your life becomes black 😄

#

If having this feature controlled by an argument is an option, I would be happy to open a pull request for it

bright glacier
#

You can always pass the files in the build directory to black explicitly.

plain atlas
#

pre-commit builds the package when the hook is in the same repository, but when using a mirror it can download from pypi and instead use prebuilt wheels

bright glacier
plain atlas
flat krakenBOT
#

Describe the bug

I have a monorepo with multiple packages, each package has a pyproject.toml that describe the package and it's dependencies.
I also have a pyproject.toml in the git root with the black config, and I always run black with the --config ./pyproject.toml flag, since I cannot rely on the configuration file automatically resolved by black (see also https://github.com/psf/black/issues/2863 & https://github.com/psf/black/pull/2525)
The problem is that the project root do...

flat krakenBOT
#

Describe the style change

Currently when run against Jupyter Notebooks, black removes semi-colons. But in Jupyter notebooks, a semi-colon has meaning—it tells the notebook to not print the output from that line (as it normally would by default for the last line in a cell). When writing notebooks for instruction, this can be annoying.

Additional context

An example of where this comes up—note after running black ...

half notch
#

Hello I am trying to use black jetbrains integration. I followed the instructions.

pip install black[d]
Requirement already satisfied: black[d] in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (23.1.0)
Requirement already satisfied: aiohttp>=3.7.4 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from black[d]) (3.8.3)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (2.1.1)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.8.1)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (4.0.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.3.1)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (6.0.2)
Requirement already satisfied: attrs>=17.3.0 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (22.1.0)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from aiohttp>=3.7.4->black[d]) (1.2.0)
Requirement already satisfied: colorama in c:\users\\desktop\statwolfbot\test\venv\lib\site-packages (from yarl<2.0,>=1.0->aiohttp>=3.7.4->black[d]) (3.4)
#

Clicking start gives

#
  return _run_code(code, main_globals, None,
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\Scripts\blackd.exe\__main__.py", line 4, in <module>
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\blackd\__init__.py", line 13, in <module>
    raise ImportError(
ImportError: aiohttp dependency is not installed: No module named 'aiohttp'. Please re-install black with the '[d]' extra install to obtain aiohttp_cors: `pip install black[d]`
half notch
lament crow
#

It's most likely that the path to black you have is not the same black installation that you installed while following the instructions

#

assuming you ran the pip install command exactly as shown in the instructions, can you show the output of pip --version

half notch
#

I am not at my PC rn. This is likely true. I remember that when running pip list black was shown but no black[d] is this normal?

lament crow
#

that's normal

#

installed extras wouldn't show there

half notch
lament crow
#

I wanted the output

#

aside from version it also shows the path

#

which is what I cared about here

half notch
#

Would it make sense to install black[d] globally instead of on the venv? Than it would be easy to get the right path.

But I'm not at my PC rn so I will have to try it later.

lament crow
#

you're installing it in a venv?

#

that is the issue

lament crow
# half notch

You're not pointing at the executable in a venv here

half notch
#

Ok, I will uninstall and reinstall globally that should fix it. Or at least make it so I can manually tweak the path a bit.

#

Thank you

flat krakenBOT
#

Description

This PR removes the Dockerfile as it is not required for the use case of this fork. The Dockerfile is used to define the environment and dependencies for a Docker container. However, as we do not plan to use Black in a Docker container, we can safely remove this file.

Checklist

  • [x] Add an entry in CHANGES.md to inform users about the removal of Dockerfile
  • [ ] Add / update tests if necessary
  • [ ] Add new / update outdated documentation

By removing...

dense jungle
#

^ is apparently what they're working on

bright glacier
#

Huh.

slow ibex
# half notch

why are you hiding your username if you send it in next message? 🤔

#

just curious

drowsy sonnet
dense jungle
#

and they deleted all the docs

drowsy sonnet
#

Very weird.

flat krakenBOT
#

Describe the style change

Black will sometimes split the .get() function for dictionaries in a not so easy to read way.

Interestingly, it will also sometimes split it in an acceptable fashion, depending on the length of the line and/or components of the line.

Examples in the current Black style

Both of these are not great:

a_dict = {}

for _ in a_dict.get("some_really_long_key_name_to_make_this_line_too_long", {}).get(
    "another_key", ["defa...
haughty summit
#

I'm trying to use Black with vim but I'm getting this error...I see that the vim script is trying to use a different python...anyway to make black use my pyenv python instead?

haughty summit
flat krakenBOT
#

#3219 (by @stinodego) introduced inference of the target versions for black from the requires-python project metadata in pyproject.toml. However, it was not implemented correctly.

The rules for the comparison operators in requires-python is documented in PEP 440.

For example, >3.7,3.7,3.7.0,3.7.0,3.7,<3.10, so they should give the same results.

I re-implemented the inference code. I will open a pull request as soon as I ...

flat krakenBOT
#
flat krakenBOT
#

Fixes #3581.

The old algorithm checked, for each target version 3.X, whether 3.X (which is roughly the same as 3.X.0) is contained in a version specifier that was modified from the requires-python project metadata to be less strict regarding patch versions. One problem of it was that, for a requires-python value of ">3.X" (which means the same as ">3.X.0"), it concluded that target version 3.X is not supported although Python versions >= 3.X.1 are included in the version specifier. I f...

bright glacier
#

Wow 'kay, that's a complicated patch.

#

OK I also need to fix diff-shades.

flat krakenBOT
#

Tests fail against setuptools 67.3.0:

==================================== ERRORS ====================================
____________________ ERROR collecting tests/test_blackd.py _____________________
tests/test_blackd.py:11: in 
    from aiohttp import web
/usr/lib64/python3/site-packages/aiohttp/__init__.py:212: in 
    from .worker import GunicornUVLoopWebWorker, GunicornWebWorker
/usr/lib64/python3/site-packages/aiohttp/worker.py:11: in 
    from gunicorn.config import Acces...
#

Description

https://setuptools.pypa.io/en/stable/history.html#v67-3-0

Added deprecation warning for pkg_resources.declare_namespace.
Users that wish to implement namespace packages, are recommended
to follow the practice described in PEP 420 and omit the
init.py file entirely.

However, projects (for example, zope) may use pkg_resources's namespace. This warning can be ignored.

Fixes: https://github.com/psf/black/issues/3585

flat krakenBOT
flat krakenBOT
#

Describe the bug

Black doesn't fully honor #fmt:off on line before #fmt:on, it moves comments.

To Reproduce

lambda_fields = {
    # fmt: off
    "full_name": lambda x: x.display_name,
    "publication_status_as_label": lambda x: x.professional_validation_workflow.get_publication_status_display() if x.professional_validation_workflow else None,  # NOQA: E501
    "transition_state": lambda x: x.professional_validation_workflow.transition_state if x.profes...
flat krakenBOT
flat krakenBOT
#

#3489 wraps multiple context managers in parentheses when targeting Python 3.9+, but async with statements aren't handled.

We noticed this in the review of #3589, but the fix is different enough that I'm filing a separate issue and will send a follow-up PR.

Example: https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AIWAK9dAD2IimZxl1N_WmufDs0LojAMwSd5y6tVHFECi48em1NmrZSWd-aOQDsyxUoj0wG4N0KjynelfrUIzSWL64h5VoX_mCOwgMPULx38--l2ByPDULdy3kY55NpHvpodxXDskAGNjzD...

flat krakenBOT
#

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

This is a similar to but not exactly the same situation as in https://github.com/psf/black/issues/3576, where black's current behavior causes the inferred project root directory to be the file system root directory (/), which makes it difficult to set up exclude paths in black's config file.

In our situation, we also have a multi-language monorepo with multiple pyproject.toml-based Python packages, but we also have...

slow ibex
#

black is formatting -2**3 as -(2**3)
why?

#
>black -c "-2**3"
-(2**3)
>black --version
black, 23.1.0 (compiled: yes)
Python (CPython) 3.11.0
#

it is a bit weird IMO

dense jungle
slow ibex
#

in math when you write -a^b it always mean -(a^b)
i think it is obvious enough that -a**b mean -(a**b) and not (-a)**b

#

i dont like this behaviour 😔

lament crow
#

I don't think it's universally true across languages though it is common. But either way, my first instinct is that unary operators bind most tightly (and in some languages aren't treated as operator during parsing but rather a part of the number) so even if mathematically it makes sense, I wouldn't be sure that this is how Python behaves. It all comes down to avoiding a potential confusion point.

bright glacier
#

I hate GHA sometimes..

plain atlas
#

what happened?

bright glacier
#

It's just completely stuck in the "Queued" state.

#

It's also uncancellable.

plain atlas
#

interesting

#

ooh i noticed something else

#

do you mind if i make a pr?

bright glacier
#

go ahead

plain atlas
#

OH

#

huh

#

interesting

half meteor
plain atlas
bright glacier
#

That explains why everything GHA seems to be broken.

plain atlas
#

thanks, apparently its an outage @tight bone

tight bone
flat krakenBOT
#

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

Right now, if a file parsing because of invalid type comments (even if the code runs just fine), black won't format the file.

For example:

import typing

def foo(
    # type: typing.List
    bar,
):
    print(bar)

foo(10)

While the code still runs:

$ python3 asd.py            
10

Black no longer formats it:

$ black asd.py        
error: cannot format ...
slow ibex
#

Why type comments are still supported?
I thought they are useless since annotations exists

#

Mypy is also raising SyntaxError if there is invalid #type:smth inside code.
It happens very often to me when i comment big parts of code, because annotation type: smth becomes #type: smth and it is invalid type comment

dense jungle
slow ibex
#
def f(
    type: type[int],
) -> int: ...
# after commenting out it becomes this:
# def f(
#     type: type[int],   ## <- this is a syntax error, very annoying
# ) -> int: ...

I never thought about # type: ignore like a type-comment, that's interesting

plain atlas
flat krakenBOT
late dewBOT
#

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

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

flat krakenBOT
#

Describe the bug

A file containing a line with type: in a comment block breaks black.

To Reproduce

  • create a python file with the following content:
# this is a test
# type: foo
# breaks it

def foo(a,  b):
    pass

(note double space between function parameters to cause black to reformat)

  • run black:
$ black broken.py
error: cannot format broken.py: cannot use --safe with this file; failed to parse source file AST: invalid syntax (, li...
flat krakenBOT
#

Describe the style change

I'm not sure if this is intended or not, but I noticed that sometimes in Black >=22.12.0 a trailing comma will trigger wrapping the concatenated string in parens, which otherwise wouldn't take place (if there was no trailing comma).

The suggestion is to make it so that the presence of the trailing comma would have no bearing on whether the concatenated string will or not be wrapped in parens.

PS: In this particular case the trailing commas are added's by...

late dewBOT
#

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

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

flat krakenBOT
#

I have some code that uses one of a few different files. So I'm commenting out certain lines to switch between files.

But the combination of Path, /, and a commented out line results in incorrect behaviour.

Workaround is to put a comma at the end of the line.

Black https://github.com/psf/black/commit/4a063a

[Playground link](https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AD8AJddAD2IimZxl1N_WlsgJGL5Th9rwn0ffOInnwH3UJGLFUg2uan3GmixKnBQYx-AdWcO8...

slim stirrup
#

!e [3.10] <print("You Are Hacked!")>

#

<@&267628507062992896> How To Check Code?

#

!e

late dewBOT
#
Missing required argument

code

slim stirrup
#

!e code

late dewBOT
#

@slim stirrup :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     code
004 | NameError: name 'code' is not defined
slim stirrup
#

print("You Are Hacked!")

#

hell

#

what the hell

#

🤬

spring ether
#

@slim stirrupthis channel is for the black formatter project; please go to #bot-commands

soft stag
#

oh wow
That moment when you throw your code into black, and it just spits out the exact same thing!
feels nice

flat krakenBOT
flat krakenBOT
restive creek
#

hello ?

lament crow
restive creek
#

what is this

lament crow
#

Read the channel topic

restive creek
#

i now but what is the project about

lament crow
#

The channel topic explains it

#

you can go to the link there to learn more

restive creek
#

ok thanks

flat krakenBOT
flat krakenBOT
#

My environment is: python = 3.11.1, black = 23.1.0
the following is the info of commandpoetry show black:

 name         : black                              
 version      : 23.1.0                             
 description  : The uncompromising code formatter. 

dependencies
 - click >=8.0.0
 - mypy-extensions >=0.4.3
 - packaging >=22.0
 - pathspec >=0.9.0
 - platformdirs >=2

The code that black failed to skip:

join(
    packages,
    func.coalesce(ord...
civic ore
#

I'm curious what are black devs thoughts on changes that https://github.com/google/pyink makes. I know some changes that have been upstreamed already, but the point 1 and 3 in the readme are ones that have pushed me away from black historically.

(I guess maybe also 2, but I suspect that one will be very controversial :)

GitHub

Pyink, pronounced pī-ˈiŋk, is a Python formatter, forked from Black with a few different formatting behaviors. - GitHub - google/pyink: Pyink, pronounced pī-ˈiŋk, is a Python formatter, forked from...

dense jungle
lament crow
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
#

<!--
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 `...
half meteor
flat krakenBOT
#

Describe the style change

It's possible to have line wraps in the body of a lambda if the lambda expression as a whole is parenthesized, or used in contexts such as function arguments. Currently black would give the wrapped lines the same indent as the line that lambda is on, which could cause confusion. I propose to have black automatically parenthesize the lambda's body so it could be further indented.

Examples in the current Black style

some_func = (
    la...
flat krakenBOT
flat krakenBOT
#

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

Black will currently not reformat this:

from typing import Union
a: int|float = ...
b: float|int = ...
c: Union[int, float] = ...
d: Union[float, int] = ...

which leads to some messy code when the type list gets long, but clearly the order of the types don't matter and might as well be sorted. I just had a git diff that was completely unnecessary, and it makes it harder to see if two somewhat complex...

flat krakenBOT
#

Describe the bug

Using multiple # fmt: skip in the same expression causes an INTERNAL ERROR.

To Reproduce

The first example (a) works but all others fail:

a = (
    "this should "  # fmt: skip
    "be fine"
)

b = (
    "this is "  # fmt: skip
    "not working"  # fmt: skip
)

c = (
    "and neither "  # fmt: skip
    "is this "  # fmt: skip
    "working"
)

d = (
    "nor "
    "is this "  # fmt: skip
    "working"  # fmt: skip
)

e ...
flat krakenBOT
flat krakenBOT
#

Description

Fixes #3438.

This isn't put in preview style because:

  1. Already formatted code always has the extra blank line, so it shouldn't change already formatted code and doesn't violate the stability policy.
  2. This unblocks us from upstreaming the incremental formatting patches in Pyink, and we don't want to require --preview (in at least in 2023) to use this feature. It would also make integrations with IDEs / pre-commit harder if we require --preview.

##...

silent apex
#

i wonder how they found their way to the black issue tracker from ruff

mint barn
#

Guyssss, how do I skip check for one line in Black?

bright glacier
flat krakenBOT
flat krakenBOT
dense jungle
#

hm tests are broken on main

flat krakenBOT
silent apex
#

i dunno, i don't work on black

bright glacier
#

I'll take a look at that PR tomorrow Jelle. I need sleep.

flat krakenBOT
half meteor
dense jungle
flat krakenBOT
plain atlas
#

hey where does black store its cache?

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

Running black with a pyproject.toml, where "extend-exclude" is set to ignore a specific file dose not work and the file is formatted when black is run.

To Reproduce
Make the following Dockerfile:

FROM mcr.microsoft.com/vscode/devcontainers/base:0.203.5-bullseye

RUN apt-get update && apt-get install -y python3-pip

RUN pip3 install --no-cache-dir black==23.1.0 

WORKDIR /

RUN git init black-obs
WORKDIR /black-obs/
RUN git branc...
flat krakenBOT
#

Describe the bug

from atmodata.iter.tensor import (
    ThBatchInterleaver, 
    ThConcatter, 
    ThSplitter, 
    ThToDevice,
)

gets formatted to

from atmodata.iter.tensor import ThBatchInterleaver, ThConcatter, ThSplitter, ThToDevice

despite trailing comma.

On a side node: # fmt: off gets ignored.

Expected behavior

Leave my code alone if I'm specifically asking for it.

Environment

  • Black's version: 23.1.0
  • OS and Python ve...
arctic goblet
#

Hey I don't have single knowledge of git hub can you tell me how and where I can learn about GitHub

flat krakenBOT
#

Hello,

I did not dive into the issue but this can still help, so here is what happens:

I use tox to run black, mypy and unittest.

I have dataclasses with several arguments. One of the arguments was commented and was named type, such as:

@dataclass
class A:
    first: int
    # type: int

Even though it was commented out, I have the following error message:
error: cannot format ..../.../: cannot use --safe with this file; failed to parse source file AST: expec...

flat krakenBOT
#

Describe the style change

If a literal string consists of multiple smaller strings concatenated via adjacency, then prefer to place each smaller string on its own line.

In Python "abc" and "a" "b" "c" are two identical strings. However, developers typically prefer the first style, as it is shorter and has less visual noise. Then, the only situation where the second style might be useful is if you want to juxtapose strings vertically:

"a"
"b"
"c"

Right now, ...

flat krakenBOT
#

Describe the style change

If a function takes a single argument which is a list, set, dict, or string, then the delimiters for those expressions can be immediately adjacent to the function's parentheses.

This would save both horizontal and vertical space, while also improving readability.

Examples in the current Black style

foo(
    [
        100,
        200,
        300,
    ]
)
bar(
    {
        "alpha": 1,
        "beta": 2,
        "gamma": ...
flat krakenBOT
#

Describe the bug

We are using latest black 23.1.0 and it is putting .format after string making line longer than required.

Solution is to use experimental-string-processing however it will probably be removed due to its functionality moved to future.
However the problem is that future contains also other improvements and we don't want the style to change with each black upgrade.

To Reproduce

Black configuration:

[tool.black]
line-length = 120
target-version = ['py...
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
half meteor
#

Just checking, any chance there will be a new Black release soon?

dense jungle
half meteor
half meteor
bright glacier
#

For anyone who is paying attention here, just an FYI that I've stepped away from maintainership of Black for the time being. I'll be around to help out with anything that may be within my domain (CI/automation/docs), but I'm not actively following Black's development any longer.

dense jungle
dense jungle
flat krakenBOT
flat krakenBOT
#

Describe the bug

Black hangs indefinitely trying to format a file with ridiculously long nested dicts. I presume it does eventually complete the task, but I haven't left it long enough to see how long that would actually take.

To Reproduce

  1. Copy and paste this file into a .py file: repro.txt
  2. Run black on it
  3. Wait

Expected behavior

This is very odd code, so I don't necessarily expect black to be ...

bright glacier
#

Congrats! 🎉

flat krakenBOT
#

Describe the style change

Examples in the current Black style

from typing import Sequence


very_very_very_very_very_very_very_very_long_expression = 'foo'
if isinstance(very_very_very_very_very_very_very_very_long_expression, Sequence) and not isinstance(
    very_very_very_very_very_very_very_very_long_expression, str
):
    print('foo')


another_very_very_very_very_very_very_very_very_long_expression = False
if (
    very_very_very_very_very_...
flat krakenBOT
flat krakenBOT
#

any way format from a line to line into a multiline, based on length?
this for functions but also other types of constructs

e.g. something like this - (to be more compact)
input

training.train_regular(
                "cpu",
                world_size,
                config["Processing"]["data_path"],
                config["Job"],
                config["Training"],
                config["Models"],
            )

output

training.train_regular("cpu", world_siz...
flat krakenBOT
#

Description

This PR aims to minimize the number of configuration files for the project. Instead of a separate .coveragerc and mypy.ini, we now would have all the configurations within the pyproject.toml file leading to a overall minimal code structure.

Checklist

  • [x] Add an entry in CHANGES.md if necessary? (skip news ??)
  • [x] Add / update tests if necessary?
  • [x] Add new / update outdated documentation?
tough sage
#

it just reads the file and has a list of mistakes, then if it sees one of those in your code it will re-format it i'm guessing

barren brook
#

Hey guys, long time 🙂

#

oo richard stepped down??

solid adder
#

Yes

exotic stratus
#

Does installing black[d] implicitly install black as well? I've always installed both via pip so far, but my IDE is now stating that black is redundant with black[d] present

exotic stratus
#

Thank you

#

Also found out that I can merge package extras as psycopg[binary,pool], nifty stuff

barren brook
#

Is psf/black#2787 still needed?

toxic stormBOT
flat krakenBOT
flat krakenBOT
#

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

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

Code before:

def asdf_asdf_asdf_asdf_asdf() -> my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None:
    pass

Black formatted to:

def asdf_asdf_asdf_asdf_asdf() -> (
    my_module.Asdf | my_module.AnotherType | my_module.YetAnotherType | None,
):
    pass

The trailing comma is incorrect, see [playground](https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADcAH1dAD2IimZxl1N_WlbvK5V8JNI78iDZsHigDVyj...

turbid dagger
#

The black formatter just formatted the pygame argument in this way. Maybe I am biased but I find this style of formatting less readable…
I am open to discussion

slow ibex
#

What do you think is more readable?

vague pewter
#

None of the above?

flat krakenBOT
flat krakenBOT
mint barn
#

Short question about black: I use the option --no-color but black's output is still colorized. Especially the blue characters are difficult to read on the black background of my terminal. How can I switch off colorized output of black altogether?

#

Looks great ofcourse, but I don't need this.

#

And I can't read it

lament crow
# mint barn

Based on the documentation of that option, it only determines whether Black returns a colored diff or not (when --diff is used).

#

If this is something that Black maintainers want to change, this should, presumably, be as easy as setting ctx.color (ctx being click.Context) to the value of color flag

mint barn
flat krakenBOT
#

Describe the style change

Examples in the current Black style

s1 = (
    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    'bbb"bbb"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
)

s2 = (
    'aaa"aaa"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
)

formated to (black --preview test.py):
...

flat krakenBOT
#

This model is a decision tree classifier that predicts whether a person will buy a car or not based on their age and income.In this example, the X array contains the input data, which consists of age and income values for eight different people. The Y array contains the corresponding output values, which indicate whether each person bought a car or not.

The decision tree classifier is created using the DecisionTreeClassifier class from scikit-learn. The fit method is then called to train t...

nova tinsel
#

that seems.. very random

dense jungle
#

some things we are not meant to understand

flat krakenBOT
pearl spruce
#

I made a tool that makes Python CLI tools start much faster. With it, I can run black on a few files in 10-20ms on my laptop, vs. at least 120ms for the mypyc-compiled version. Especially great when combined with pre-commit in git pre-commit hooks.

Happy to get some early adopters checking it out!
https://github.com/taleinat/jumpthegun

dense jungle
pearl spruce
# dense jungle That sounds awesome, thanks! Do you have any resources on how it works? I assume...

Hi Jelle! I haven't written anything about how it works yet. I'll add more documentation at some point.

Indeed, for each CLI tool, JumpTheGun runs a background daemon which loads Python and does the imports in advance. This is run the first time the tool is run via JumpTheGun. It stays running until the tool hasn't been run for a while (4 hours by default).

To stop the daemon, run jumpthegun stop <tool-name>, or just kill the daemon process.

flat krakenBOT
#

Describe the style change

Black treats standalone expressions containing boolean operators differently from those containing other operators.

Examples in the current Black style

This code is unchanged by Black:

# before and after
foooooooooooooooooooooooo and barrrrrrrrrrrrrrrrrrrr and bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzz and quxxxxxxxxxxxxxxxxxxxxxxxxxxx
def f():
    foooooooooooooooooooooooo and barrrrrrrrrrrrrrrrrrrr and bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzz and qu...
flat krakenBOT
bright glacier
#

FYI please feel free to CC me for anything mypyc related. I'm on the mypy(c) core team and I'd be happy to help!

half meteor
pearl spruce
pearl spruce
pearl spruce
# half meteor Since you are already here, how can I build the Black mypyc wheels locally in th...

So looks like I did the following to build a mypyc-based wheel only for my local Linux machine:
0. Have Docker installed, the Docker daemon running, and permission to run the docker cli.

  1. Create a venv and run pip install cibuildwheel
  2. cibuildwheel --platform linux --help
  3. cibuildwheel --platform linux --print-build-identifiers
  4. cibuildwheel --platform linux --only cp310-manylinux_x86_64
  5. pip install ./wheelhouse/black-22.12.1.dev37+g18fb884-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
bright glacier
#

Thanks Tal. I've never actually used CIBW locally. (anyway CIBW is amazing <3)

flat krakenBOT
slow ibex
pearl spruce
flat krakenBOT
#

Describe the bug

I've run across an issue where the following code gets formatted not very nicely. This particular snippet should IMO already satisfy Black with line_length=120.

def main(
    client: AppRole,
    role_name: str = Option(..., help="The name of the role to generate a secret ID for", metavar="ROLE_NAME"),
    secret_id: str | None = Option(
        None,
        help="A custom secret ID to use. If not specified, one will be generated.",
        metavar="...
gilded scarab
#

Hello everyone, is it possible to somehow start Black immediately automatically, that is, when I start PyCharm, does it also start in a separate terminal?

flat krakenBOT
flat krakenBOT
flat krakenBOT
pearl spruce
pearl spruce
#

I'll just share this here, here's my current preferred way to have black (via pre-commit) run automatically on code changes in PyCharm Professional via its "File Watchers" feature:

gilded scarab
#

Thanks

flat krakenBOT
#

Describe the style change
When assigning multiple similar values with different-length variable names, aligning the = (assignment) operators using spaces should be allowed. In my opinion, this allows the reader to assess the differences in the literals (or function calls) more easily than when the = are scattered over different columns.

Examples in the current Black style

#!/usr/bin/env python3
"""
VT100 escape sequences for text foreground color
"""

black ...
flat krakenBOT
exotic stratus
#

black doesn't enforce some sort of an opinionated docstrings format?

exotic stratus
spring ether
#
import os, json, math, csv, fasttext, nltk, spacy, subprocess, copy, random
import pandas as pd
import numpy as np
import os, json, csv, fasttext, nltk, spacy, subprocess, copy

why didn't black put each of these on different lines?

#

and remove duplicates?

fossil scaffold
#

Does anyone use Black on Airflow DAG files?

fossil scaffold
fossil scaffold
#

For an Airflow DAG I'm non-plussed by the many lines of graph setup that went from:

[
    dataset_service_tablename_A_ready_sensor,
    dataset_service_tablename_B_ready_sensor,
    dataset_service_tablename_C_ready_sensor,
] >> prepare_cluster >> [
    parallel_job_on_A,
    parallel_job_on_B,
    parallel_job_on_C,
    parallel_job_on_A_and_B,
    parallel_job_on_B_and_C,
]

to

(
    [
        dataset_service_tablename_A_ready_sensor,
        dataset_service_tablename_B_ready_sensor,
        dataset_service_tablename_C_ready_sensor,
    ]
    >> prepare_cluster
    >> [
        parallel_job_on_A,
        parallel_job_on_B,
        parallel_job_on_C,
        parallel_job_on_A_and_B,
        parallel_job_on_B_and_C,
    ]
)```
#

It's mentioned that --preview has some cases where parenthesis aren't added… but this doesn't seem to be one of them

fossil scaffold
#

The extra indentation makes it stand out next to lines like:

cleanup_cluster >> send_message
cleanup_cluster >> [validate_A, validate_B] >> update_status
cerulean shore
#

Is there any way to influence how Black wraps long boolean expressions (chains of and/or)?

I think it formats this extremely awkwardly here:

# Before
return (
    self.file >= other.file
    and listify(self.version) > listify(other.version)
)

# After Black:
return self.file >= other.file and listify(self.version) > listify(
    other.version
)

Why would Black line-break inside a parameter list when it could instead break on the and?

If I add a third condition to this expression (like and fooz == baz) it will format it how I originally did. Is there any way I can influence Black to do this sooner, like a trailing comma can do for dicts and argument lists?

fossil scaffold
#

Maybe it should keep input expression parens. IDK there's probably cases were removing excess parens also looks better.

flat krakenBOT
#

PEP-597 added an option to warn when the encoding argument to open() is omitted and the default locale-specific encoding is used, because this can cause bugs when the locale is incorrectly assumed to be e.g. utf-8, which may not be the case on Windows, or various systems in e.g. Japan.

Setting PYTHONWARNDEFAULTENCODING=1 in CI, and fixing any existing issues, will ensure that downstream projects can also adopt this check without awkward workarounds.

flat krakenBOT
flat krakenBOT
#

Describe the style change

The blank lines between a function's definition and its docstring currently get removed by Black. However, it does not do the same thing for classes.

Current Black changes

def f():

    """The line above gets removed."""
    return 0

becomes

def f():
    """The line above gets removed."""
    return 0

but

class C:

    """The line above stays."""

is not modified by Black.

*Desired style...

late dewBOT
#

:x: failed to apply.

ivory quest
flat krakenBOT
#

Describe the style change

In a multi-line function-call expression, where each parameter is on its own line, it would be great to add spaces around the = signs.

Examples in the current Black style

some_function(
  param1="string value",
  param2=1 + 7 + 11,
  param3=[
    "one",
    "seven",
    "twelve",
  ],
  param4="another long value", 
  param5=some_other_function_call(*args),
)

Desired style

some_function(
  param1 ...
flat krakenBOT
#

Description

Hi! It looks like you have some special handling for # type: ignore comments to avoid moving said comments around due to positional meaning. I think this same special handling should also apply to # pyright: ignore comments.

Checklist - did you ...

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

Describe the style change
After 12 spaces (3 tabs), the assignment of a long string into a dictionary key will split the dictionary and key with new line. This will mostly happen in a class method (example below).

To reproduce:

  1. add 12 spaces (3 tabs) in front of a dictionary value assignment
  2. assign a long string that will exceed 88 line length limit

Original Code (take a look on line with (context["header"]))

class DjangoViewsClass(TemplateView):
...
flat krakenBOT
#

Describe the style change

Strange indentation of a long assert statement, in --preview (it works correctly in the stable branch).

Examples in the current (preview) Black style

assert (
    result
    == "Lorem ipsum dolor sit amet,\n"
    "consectetur adipiscing elit,\n"
    "sed doeiusmod tempor incididunt\n"
)

Desired style

assert result == (
    "Lorem ipsum dolor sit amet,\n"
    "consectetur adipiscing elit,\n"
    "sed ...
fossil scaffold
#

It seems I misinterpreted this channel as discussion on style choices or unexpected changes

dense jungle
fossil scaffold
#

It currently looks like a place to catchup on issue updates… or maybe get some help in usage? I just want to be sure I understand the meaning of "the development and usage of the tool"; whatever works for the primary users.

lament crow
#

You can talk about pretty much everything related to Black so that would include things like why Black chooses some style, development, usage, issues people encounter, features they want. Some of these things often make more sense as a trackable Issue on GitHub but there's no a solid line between them

#

You only have seen issue updates here recently probably because there wasn't much to talk about. I think Jelle is now the main active maintainer so he doesn't have to talk with say, ichard, about Black that often

flat krakenBOT
#

Describe the bug

Multi-line short raw strings do not get merged properly into a single string.

To Reproduce

For example, take this code:

x = (
    r"first " 
    r"second"
)

The resulting string is:

x = r"first " r"second"

Expected behavior

x = r"first second"

Environment

https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ACQAF1dAD2IimZxl1N_WmyLkeQzBfBJMV91W5jeUe06WkTDih...

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

To Reproduce

Unsure, but happens to me consistently with the following:

  1. start blackd
> blackd --bind-port 45484
blackd version 23.3.0 listening on localhost port 45484
  1. Send some format requests (here we sent heaps of requests, only two came back, the rest just hung on the connection.)
> blackd --bind-port 45484
blackd version 23.3.0 listening on localhost port 45484
INFO:aiohttp.access:127.0.0.1 [28/Apr/2023:00:03:22 +0000] "P...
flat krakenBOT
#

Describe the bug

When using """ """ to define multi-line strings, I've noticed that if the user indents with tabs, black seems to replace each additional indentation beyond 1 tab with too many spaces.

To Reproduce

For example, take this code: (sorry about the , code blocks in Markdown don't seem to like tabs, ironically enough). If you replace each with a tab set to 4 spaces for example, you will be able to reproduce this issue.

def test():
"""
Test of indent...
fossil scaffold
#

Does anyone have an argument script for winning space-over-tabs by arguing tabs are anachronistic metal things on a teletype and have little place left in files (other than formats like tsv)?

lament crow
# fossil scaffold Does anyone have an argument script for winning space-over-tabs by arguing tabs ...

I don't because in an ideal world I think that tabs actually are actually better about a lot of things, it's just that this doesn't matter because it's more important to use the usual code style for your language of choice. And as said, tabs are better in an ideal world and we don't get to live in one. For example, some of the advantages of tabs can also be disadvantages - the ability for every developer to configure tab width as they wish is a very good thing but the problem with that is that this means that different programs may render tabs differently (on single user's computer) and they don't all allow you to configure them to render things differently. For example, it's popular for some software to assume that one tab is 8 spaces, i.e. tabs in terminals were always typically 8 spaces and some of the command-line applications depend on it which makes it hard to set them to render as 4 spaces even if your terminal applications gives you the choice. Spaces don't have such problems since 1 space always has a width of a single character.

#

tabs are better in a vacuum, spaces are better in practice is basically my point

fossil scaffold
#

Its true that if tabs rendered the same in the terminal, an editor or ide etc they'd be a non-issue and a byte-savings. But they were intended to move the print head to the next bit of movable metal tabstop, so they're intended to be configurable.

lament crow
#

if they actually were configurable then that would be fine

#

my point is that they aren't

#

not everywhere

elder tusk
flat krakenBOT
#

Black enforces that every comment starts with a space, except if the comment starts with a hardcoded list of black.comments.COMMENT_EXCEPTIONS (COMMENT_EXCEPTIONS = " !:#'"). These were added over time to support particular tools that treat certain comments specially. We occasionally get requests to treat more comments specially (#3557) or confusion because of the inclusion of particular characters (#3036). I am opening this issue to focus the discussion and arrive at an overall solution....

dense jungle
#

I think that's enough closed issues for today

bright glacier
#

That explains why my email is blowing up (yeah I'm still watching the repository).

#

that's one more month where the issue count went down!

dense jungle
#

that's kind of depressing, I only made up for one month of growth?

elder tusk
#

every now and then i close like a dozen mypy issues. but mypy’s net issue growth is still like 30/month

bright glacier
#

anyway, you also dealt with this month's growth too so you've closed more issues than it may appear on that chart

flat krakenBOT
#

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

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

Description

I followed the docs to make Black format my %%writefile blocks, but in blind copy-pasting I realized %%writeline was a nonexistent magic (and it was probably meant to be %%writefile).

See the full list of built-in magics: https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-writefile

Checklist - did you ...

  • [ ] Add an entry in CHANGES.md if necessary?
  • [ ] Add / update tests if necessary?
  • [x] Add new / update out...
cedar bluff
#

Hello! Our team have the diff black formatting result on each developer env. How we can debug it? And consider what Black rules we should add to pyproject.toml for got the identical result

dense jungle
#

consider setting required_version in pyproject.toml to standardize on a version

cedar bluff
dense jungle
#

if you really have different formatting with the same version, that's a bug and you should report it. But my experience is that when people report this, they're almost certainly not running the version they think they are running. Setting required_version = "23.3.0" in your pyproject.toml should help ensure that, at least for versions new enough to support that option

cedar bluff
flat krakenBOT
cedar bluff
dense jungle
#

I have a PR to expand that list but it had some weird sphinx errors and I haven't gotten around to finishing it 😦

dense jungle
dense jungle
#

finally got CI green on that, please review!

flat krakenBOT
flat krakenBOT
late dewBOT
#

:incoming_envelope: :ok_hand: applied timeout to @rugged ridge until <t:1683139543:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

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

brave orchid
#

Any low hanging issues I could help fix over the weekend?

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

The following code can not be formatted

with (a,b): # type: something
    pass

when run with these arguments:

$ black example.py

The error is:

error: cannot format example.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_o04ck2zv.log

Oh no! 💥 💔 💥
1 file failed to reformat.

**Environmen...

flat krakenBOT
#

Some with statements can not be parsed by black.
They are unlikely to appear in real code, but they are valid python and can be parsed by cpython.

Examples

with (name_2 for name_0 in name_4):
    pass
with (a,*b):
    pass

None of these examples have a valid __enter__ or __exit__ and should fail at runtime.

black gives the following error:

error: cannot format example4.py: Cannot parse: 1:8: with a, *b:

Oh no! 💥 💔 💥
1 file fa...
flat krakenBOT
flat krakenBOT
#

Description

Okay, so basically I think this is a based feature because of the confusing nature of the implicit tupleification of getitem.

(Also it will help with https://github.com/KotlinIsland/basedmypy/issues/418)

Checklist - did you ... know ❓

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

why in thonny black format is not working?

lament crow
#

thonny?

#

Ah, it's an IDE

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 `...
clever peak
#

when black converts py print(weighted_randint(1, 10, [1, 1, 1, 1, 4,5,6, 1, 1, 1])) to ```py
print(
weighted_randint(
1,
10,
[
1,
1,
1,
1,
4,
5,
6,
1,
1,
1,
1,
],
)
)

flat krakenBOT
flat krakenBOT
#

Describe the bug

Black is wrapping some type hints when using multi-line string literals.

Any type hint with an argument seems to trigger this.

A bare type hint, e.g. str does not trigger this.

To Reproduce

For example, take this code:

from typing import Final

query: Final[str] = """
  SELECT my_column
  FROM my_table
  WHERE my_column > 1;
"""

And run it with these arguments:

$ black file.py --target-version py311

The re...

fallow lance
#

Hi friends! Question: my reading of https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#how-black-wraps-lines

Black ignores previous formatting and applies uniform horizontal and vertical whitespace to your code.
// The emphasis on "ignores" is mine.

Is that I should be able to do the following tickery:

  1. Run black with my default line-length = 99. This is a no-op.
  2. Run black with line-length = 30. This will change a bunch of lines.
  3. Run black with line-length = 99 again. That should revert all the changes.

This is NOT the behavior I'm observing. (3) doesn't revert anything.
Any thoughts on this?

The bigger context is that I'm auto-adding a bunch of pyright diagnostic supressions into a codebase with black formatting and trying to make this 2 tools work together.

dense jungle
#

If you run black -C, you may get closer to your original formatting

fallow lance
dense jungle
#

short for --skip-magic-trailing-comma

fallow lance
#

🙏 thank you so much Jelle, you are always helpful

#

@dense jungle is there a similar option by any chance for the () adding?
I have this diffs now all around

-        run, _, _, expected_side_artifacts = run_with_artifacts
+        (run, _, _, expected_side_artifacts) = run_with_artifacts
dense jungle
#

no, unfortunately

#

ideally we should remove parens in cases like that when we don't need them, but it's a slow process

fallow lance
#

yeah this pyright + black interactions could be better

#

Thinking about it, it's actually not possible to improve it I think

#

You will always have the problem that you don't know which line you need to attribute the supression after the re-formatting

fallow lance
#

@dense jungle one thing I noticed is that -C doesn't respect the [] type comment syntax. I.e. it was not able to undo this

dense jungle
fallow lance
#

👍

late dewBOT
#

@hollow valley :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_NAME                0 (x)
004 |               4 POP_JUMP_FORWARD_IF_NONE     4 (to 14)
005 |               6 LOAD_NAME                0 (x)
006 |               8 STORE_NAME               1 (y)
007 |              10 LOAD_CONST               0 (None)
008 |              12 RETURN_VALUE
009 |         >>   14 LOAD_CONST               0 (None)
010 |              16 RETURN_VALUE
011 | None
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/okuqalinis.txt?noredirect

#

@hollow valley :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_NAME                0 (x)
004 |               4 POP_JUMP_FORWARD_IF_FALSE     4 (to 14)
005 |               6 LOAD_NAME                0 (x)
006 |               8 STORE_NAME               1 (y)
007 |              10 LOAD_CONST               0 (None)
008 |              12 RETURN_VALUE
009 |         >>   14 LOAD_CONST               0 (None)
010 |              16 RETURN_VALUE
011 | None
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/unosodedik.txt?noredirect

hollow valley
#

oh shit i just realised this isnt #bot-commands

#

im sorry 😓

quaint sleet
#

Is blib2to3 considered stable?
I’m working on adding structured pattern matching and parenthesized-context-manager support and as part of that effort have proposed forking lib2to3 with some features of bllib2to3 backported to it.
There are questions around just using blib2to3 instead.
See https://github.com/google/yapf/issues/1067 for more info.

GitHub

Opened after @char101 said it was okay to open a PR for this. Many thanks to them for adding match statement support for yapf!
lib2to3 is no longer maintained, this pulls in a fork of black's b...

dense jungle
#

I wouldn't be averse to making it into a separate installable project though, if there's interest

flat krakenBOT
#

Description

Checklist - did you ...

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

This is an attempt to close #3551 via an option. This is certainly a WIP but I'd like to get feedback before continuing.

  1. Is the approach via an option what you want to go for? Or do you consider reverting the style change for 2024 (as @JelleZijlstra hinted ...
quaint sleet
#

@dense jungle thank you for the update. I’ve added your comments to the referenced PR.

dense jungle
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
fallow lance
#

ok so another edge case of pyright+black interactions https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AEvAMpdAD2IimZxl1N_WmufDs0LpH-m0u1CYeUiV-mNdcgl9W4yVi-Y_0m71dk3gORdBorNlMpLUC2Q8sVZg-xGpsLzLZpzNyG2KSPeLQvxK9dMpScAOTol1exTdsQ9Xq0zWFnQEA8r_LsvFhxTkkAByrR1yAMeeoxRUjwZ1Q3Pa4ZpzKKZFUb2pwsIUdKXMcuadKspposliL5QS6Kv9zv-XHyH-7shHi3-82uorWknEnXxRFC-GmGItgxbn1Z--qDS1bHaX943n9ikSzmGczAAAACMnFawvW14VgAB5gGwAgAABp_eILHEZ_sCAAAAAARZWg==

with patch(
    "xxx"
) as get_firmware_function:
    # return_value is unknown param, whatever
    get_firmware_function.return_value = "/dev/null"  # pyright: ignore[reportGeneralTypeIssues]

This supression is getting messed up by black

Playground for Black, the uncompromising Python code formatter.

flat krakenBOT
#

Description

I would like to expand the excluded files/folder given in the default value (DEFAULT_EXCLUDES).

I would like to exclude the folders of .vscode, .pytest_cache and .ruff_cache. I tend to add these in the exclude arg of [tool.black] in my project.toml files. I can't see others wanting to run black on these unless i'm mistaken. I'm therefore wanted to upstream my excludes and save potential work for others who add this to configurations excludes.

To make it easier t...

flat krakenBOT
tawny heron
#

Is it possible to override default max line length just for a module?

flat krakenBOT
#

Description

Fixes psf/black#3659

Since the psf/black#3035, the blank lines between a function and its docstring are removed. The class docstring is special cased in the code to leave one blank line after, so that change has no effect. This PR fixes that.

BTW, but I couldn't find a test for the function case so I added one just to be sure it doesn't regress :)

Checklist - did you ...

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

Describe the bug

When calling a function to get an index for string access. The black formatter adds whitespace after the function call. Which causes a lint error in Flake8.

To Reproduce

str1 = "hello"
str2 = f"{str1} World!"
#Black inserts a space befor the ':' here. Then Flake8 see's that as an issue. E203 whitespace before ':'
print(str2[len(str1):])

#No whitespace is inserted here
print(str2[5:])

And run tox with this config:

commands ...
dense jungle
#

haven't gotten one of those in a while

flat krakenBOT
#

Describe the bug

Patterns with trailing slashes in .gitignore are not processed by black, meaning that there is an inconsistency between the files processed by git and the files processed by black. In git, trailing slashes only match directories, but it appears that normalize_path_maybe_ignore does not include trailing slashes for directory paths, leading to this inconsistency.

To Reproduce

Create a directory with the following fi...

slow ibex
# dense jungle no

I think you can format all except one module with one line length and then format only one module with other line length

dense jungle
pearl spruce
#

Would there be interest in an alternative to blackd that doesn't require modifying black at all, uses a generic protocol and client, and can be used for other CLI tools as well?

pearl spruce
#

Cool! I've been working on something like this for a while, and have recently released it. It works perfectly with black :).

In terms of maturity, it's still early stage, but I already have it integrated into my git pre-commit hooks and IDE file watchers and use it all of the time.

JumpTheGun: https://github.com/taleinat/jumpthegun

#

I'm super-curious to hear what you think about it @dense jungle !

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Description

Several new versions of mypyc has been released since the last upgrade, and they include some performance improvements which could make the compiled version of Black run faster.

https://mypy-lang.org/news.html

The latest version of hatch-mypyc allows being installed next the 1.x series of mypy.

I chose mypyc because it has already been out for a little while, and should probably be quite stable by now, but can also try a different version!

Checklist - did ...

sweet tendon
#

What is black formatter?

silent apex
#

black is an automatic code formatter for python

#

you run it on a python file, and it will convert everything to a standard style

ivory quest
#

while it's not an official formatter, it became sort of a standard in the community

ornate hedge
flat krakenBOT
silk dust
#

Failed to run Black. Whenever I try to run Black from within vscode (ctrl-shift-P > Black: Run Black), I get this error. I can run it from the command line, so I am pretty sure it isn't a Black issue per se, but this is the only plugin where I have problems like this. Hoping some kind person can show me what I am doing wrong. Thanks in advance!

flat krakenBOT
#

Black currently fails on files containing a carriage return in many positions, while Python itself is happy to treat \r as a newline.
For example:

import black
black.format_str("{\r}", mode=black.Mode())

This is obviously a trivial example, but the problem occurs for a fairly wide range of old Python code from e.g. MacOS, or when files are loaded without universal-newlines (which does still happen occasionally).

As a fix, I d...

ivory quest
flat krakenBOT
#

With current latest black, 23.3.0 (compiled: yes):

import black

code = """
assert some_long_name, (  # long __________________________ comment
        'long ___________________________________ string %s' % str(variable))
"""
black.format_file_contents(code, fast=False, mode=black.FileMode())

Specifically, this stabilizes at the second run:

assert some_long_name, (  # long __________________________ comment
        'long _____________________________...
flat krakenBOT
#

With current latest black, 23.3.0 (compiled: yes):

import black

code = """
if True:
  # fmt: off
  pass
  # fmt: on
  pass
"""
black.format_str(code, mode=black.FileMode())
Traceback (most recent call last):
  File "repro.py", line 10, in 
    black.format_str(code, mode=black.FileMode())
  File "src/black/__init__.py", line 1084, in format_str
  File "src/black/__init__.py", line 1089, in _format_str_once
  File "src/black/parsing.py", ...
rancid abyss
dense jungle
#

So if someone changes the whole file, that will be preserved

rancid abyss
#

Thanks for the clarification

flat krakenBOT
#

When running black (tested with version 23.3.0) as follows:

import black

code = """
if True:
 if True:
  # fmt: off
  pass
"""

black.format_str(code, mode=black.Mode())

This produces the following error:

Traceback (most recent call last):
  File "", line 1, in 
  File "src/black/__init__.py", line 1084, in format_str
  File "src/black/__init__.py", line 1089, in _format_str_once
  File "src/black/parsing.py", line 94, in lib2to3_parse
  File "src/blib2t...
#

Running black 23.3.0 on the following code:

class S:
 if():last_shard.accumulated_answer_json_size_bytes=(#pylint: disable=invalid-name
[0])

Produces the following output:

class S:
    if ():
        last_shard.accumulated_answer_json_size_bytes = (
            [0]  # pylint: disable=invalid-name
        )

But if we run black on it again we get the following:

class S:
    if ():
        last_shard.accumulated_answer_json_size_bytes = (
        ...
flat krakenBOT
hexed furnace
#

AWith current latest black, 23.3.0 (compiled: yes):

import black

code = """
if True:
  # fmt: off
  pass
  # fmt: on
  pass
"""
black.format_str(code, mode=black.FileMode())
Traceback (most recent call last):
  File "repro.py", line 10, in 
    black.format_str(code, mode=black.FileMode())
  File "src/black/__init__.py", line 1084, in format_str
  File "src/black/__init__.py", line 1089, in _format_str_once
  File "src/black/parsing.py", ...
dense jungle
#

That's a known bug that's difficult to fix

flat krakenBOT
#

I'm running a couple of GHA jobs, one of them being the black formatter inside an Ubuntu container on a self-hosted runner. I've noticed that after running the black formatting action there are files leftover in the _actions directory that aren't owned by the runner's user but rather by root:

ne or more errors occurred. (Access to the path '/home/ubuntu/actions-runner/_work/_actions/psf/black/stable/.black-env/lib/python3.10/site-packages/black-23.3.0.dist-info/INSTALLER' is denie...
pulsar kayak
#

!d round

late dewBOT
#

round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
pulsar kayak
#

!e

round(1/1024, 6)
late dewBOT
#

@pulsar kayak :warning: Your 3.11 eval job has completed with return code 0.

[No output]
pulsar kayak
#

!e

print(round(1/1024, 6))
late dewBOT
#

@pulsar kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.

0.000977
zenith jacinth
#

!d round

late dewBOT
#

round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
bright glacier
zenith jacinth
#

oops

flat krakenBOT
flat krakenBOT
#

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

This is the current behaviour for handling .gitignore:

https://black.readthedocs.io/en/stable/usage_and_configuration/file_collection_and_discovery.html#gitignore

If --exclude is not set, Black will automatically ignore files and directories in .gitignore file(s), if present.

If you want Black to continue using .gitignore while also configuring the exclusion rules, please use --extend-exclude.

However,...

flat krakenBOT
flat krakenBOT
#

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

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

Hi, thanks for Black - it saves me a TON of time, but even more importantly, greatly reduces my mental load when writing code.

Describe the style change

I suggest maybe it a code comment inside a parentheses should remain inside the parentheses.

Examples in the current Black style

Here's the actual use case I am running into today:

# this:
h_mincover_in = (3.5  # ft 
                            * 12)
# becomes:
h_mincover_in = (3.5 * 12)  # ft

*...

flat krakenBOT
flat krakenBOT
flat krakenBOT
#

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

I absolutely never want more than two list items on a single line, regardless of how long that line is. I can manually add a "magic trailing comma" to the final item to get this behavior for a specific case, but that's easy to forget and, when working in a team, not everyone will do this. If this trailing comma is forgotten, shorter lists will end up smooshing it on a single line, which makes for larger diffs that are more ...

flat krakenBOT
solid adder
#

@austere lava libcst's native parser is default now? Noice. Congratulations on 1.0.0

austere lava
#

Yup! Thanks

solid adder
#

@austere lava is the parser recoverable?

austere lava
#

No unfortunately

solid adder
#

any chance it will or no?

austere lava
#

We have a project called errpy that's an error recoverable parser based on tree sitter

#

It's currently powering pyre and we'll migrate libcst to it too

#

That will take a while though

solid adder
#

Ocaml, eh?

austere lava
#

No, Rust

#

It's just exposed to ocaml atm because that's what pyre eats

solid adder
#

ah, I see

#

makes sense

austere lava
#

Rust will be the lowest common denominator and there will be python/ocaml/rust apis

solid adder
#

I'm asking because there's drama a-brewin' because Python 3.12 changes its tokenizer to raise SyntaxErrors

#

and it turns out IPython was using the ability for the tokenizer to gulp invalid code to support some of their magic

austere lava
#

Aha

solid adder
#

and now they are upset as they would have to migrate to something and there doesn't seem to be anything to migrate to

#

so you could come in on a white horse and save that shit

austere lava
#

Do you have a link to the drama?

#

Sidenote: it's very hard to make a peg parser error recoverable while also keeping it usable

solid adder
austere lava
#

Oh of course the blue bird of toxicity

solid adder
#

Mastodon isn't better. Like soylent green, it's people!

austere lava
#

Well they could conceivably use libcst's tokenizer

#

I'll check it out

austere lava
#

I find that CPython's implementation of these things have conflicting goals with dev tools (performance vs UX)

#

replied on the thread, let's see what they say

solid adder
#

by the way

#

Black will be now met with new grammar shenanigans

#

f"hey {"zsol"}!"

#

this will be fun for Batuhan to work around, eh? if even possible

dense jungle
austere lava
#

Understandable

flat krakenBOT
flat krakenBOT
#

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

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

Describe the bug

When running black with --stdin-filename, the pyproject.toml configuration isn't respected if running black from a parent directory relative to the location of pyproject.toml.

To Reproduce

Suppose you have a directory structure as follows:

backends
├── pyproject.toml
└── src
    └── app
        └── main.py

where main.py has just one print statement such as print("This line is too long") and pyproject.toml has this `b...

pastel breach
#

black fails for me when run via precommit in pypy3.8 ci

flat krakenBOT
flat krakenBOT
#

This code is a little odd, but before it left it as is and now with 23.3.0, the output is changed

def changes(a, b, c="C", **kwargs):
    z, y = kwargs["a"], kwargs["b"]
    x, w, v, = (
        "X",
        "W",
        "V",
    )

def stays(a, b, c="C", **kwargs):
    z, y = kwargs["a"], kwargs["b"]
    x, w, v = (
        "X",
        "W",
        "V",
    )

With 22.x, these would both be left as is, but with 23.3.0, the changes function is changed to a tupl...

flat krakenBOT
#

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

The documentation here: https://black.readthedocs.io/en/stable/usage_and_configuration/black_as_a_server.html#usage
States: There is no official blackd client tool (yet!).
Describe the solution you'd like

Well, I wrote one for me personally, and I thought it'd be nice to give it to someone who knew how to add it to the codebase, but I'm not super dedicated, I just figured, it's probably copy/pastable into th...

flat krakenBOT
#

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

I am unsure how to cite Black in my research articles.

It would be useful to have an explicit metadata component describing how to cite Black.

Describe the solution you'd like

A CITATION.cff file could be added to the root of the repository. This would allow GitHub to automatically generate a citation in both APA and BibTeX format. Additionally, reference manager plugins such as Zotero will be able to automatic...

flat krakenBOT
flat krakenBOT
dense jungle
#

this one. black.

flat krakenBOT
#

Enterprise malware scans flag black.exe and blackd.exe due to neither binary being signed. This can be checked/verified via AuthenticodeSignature baked into Windows:

AuthenticodeSignature -FilePath black.exe


    Directory: ${super long directory}


SignerCertificate                         Status                                        Path
-----------------                         ------                                        ----
                                          No...
elder tusk
# dense jungle this one. black.

formatters should make your code easier to read. black is a little shy about preserving the AST... i find "rm" does a really good job of making my code more readable

flat krakenBOT
#

Describe the style change

Examples in the current Black style

match status:
    case ThisIsAnExampleStringEnum.this_is_example_status_one | ThisIsAnExampleStringEnum.this_is_example_status_two | ThisIsAnExampleStringEnum.this_is_example_status_three:
        print("ok")
    case _:
        print("not ok")

Desired style

match status:
    case (
        ThisIsAnExampleStringEnum.this_is_example_status_one
        | ThisIsAn...
vocal escarp
#

In this PyCon talk, Lukasz said that black uses asyncio to parallelize formatting: https://youtu.be/oVhJAVS3g00 . But the talk is mostly about ProcessPoolExecutor and shared memory. I didn't think asyncio would help with compute-intensive work.

You've heard it many times: the GIL is a problem for using all your CPU cores in one program. Among the generally accepted solutions there's multiprocessing, a way to orchestrate a group of worker processes to spread CPU load over many cores. This solves the problem for many use cases but if you have a lot of data to pass around there and back a...

▶ Play video
elder tusk
late dewBOT
#

src/black/concurrency.py line 119

async def schedule_formatting(```
elder tusk
#

the ProcessPoolExecutor is started a couple lines above that

vocal escarp
bright glacier
#

frankly I don't understand why we use asyncio.

#

Is it used as a better abstraction over using multiprocessing directly?

flat krakenBOT
#

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

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

Description

Avoids a Python 3.12 deprecation warning.

Subtle difference: previously, timestamps in diff filenames had the +0000 separated from the timestamp by space. With this, the space is there no more.

Checklist - did you ...

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

whats this??

silent apex
#

black is an automatic code formatter for python code

#

check out the link in the channel description for more info

flat krakenBOT
#

Description

Fixes #3716

The current phrasing of the Flake8 section of the line length documentation is very open.

This PR makes it more concise and explicit, as well as change the max-line-length example when using flake8-bugbear to 80, as explained in #3716.

Checklist - did you ...

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

Black fails with incorrect encoding. See the following example:

example.py

# coding: mypy
def f(x: int) -> int:
    return x + 1

The expected behavior:

no error.

The actual output on black

error: cannot format /home/xxm/Desktop/example.py: unknown encoding: mypy

Oh no! 💥 💔 💥
1 file failed to reformat.

How to reproduce it:

  1. store the above code in a single python file "example.py"
  2. run with the command "black example.py"

...

lament crow
#

Does mypy have its own codec?

dense jungle
flat krakenBOT
#

I have an import (which is already formatted in a way that doesn't violate max-line-length)

from base.tests.blabla.v1.something.even_more_deep \
    .this_is_one_file.this_is_also_something.one_file import Ship

after running black with the command

 black -l 99 --preview ./

the import would be formatted as

from base.tests.blabla.v1.something.even_more_deep.this_is_one_file.this_is_also_something.one_file import (
    Ship,
)

which would violate the --max-...

lament crow
#

because it would change the AST

#

i.e. how the code behaves

#

there are other tools that can reorder imports already

ivory quest
#

ruff

lament crow
#

I would have said the same, yeah

covert ridge
#

Hi guys, girls, people

This is presumably a really common request so hoping someones written someway around it

As a developer I want to be able to postpone triggering the file watcher if there is another change in certain short period of time ("quiet period") - i.e. a developer touches one line in the scope of watched files, saves the file and a second later she makes another change, thus triggering another run.

What steps will reproduce the problem?

Enable file watchers.
Make a change in your files, triggering the file watchers to start the build
Realize you wanted to make another tiny change in some other file.
Waiting for the previous build to finish takes lot of time

What is the expected result?
When the developer makes the first change a sort of "quiet period" starts (e.g. 10 seconds) at the moment waiting out any other potential change in watched files the developer might still want to make. If she does not make another change during the quiet period, file watchers start the build. Any change during this quiet period prolongs the quiet period (resets the timer).
Ideally the length of the quiet period would be configurable.

What happens instead?

currently there is not an option to set the quiet period

#

Also not only does it avoid waiting, but sometimes im halfway through writing a line and it reformats and moves my cursor which is infuritating

really good tool though

dense jungle
flat krakenBOT
rare niche
#

Hi all, I have a question. I write some Python code in markdown document.

Just like this:

class Solution:
    def pivotInteger(self, n: int) -> int:
        for x in range(1,1000):
            if (1 + x)* x= (x + n) * (n - x + 1):
                return x
        return -1

How can I automatic format the code with black?

fallow lance
rare niche
# fallow lance I'd probably use https://black.vercel.app/ to copy-paste the snippets back and f...

Thanks for your sharing. I think it would be better to format the python code in markdown document automatically.

https://github.com/doocs/leetcode/blob/main/run_format.py#L62-L84 Here is my current solution. And I am looking for a better way 🙂

GitHub

😏 LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解 - leetcode/run_format.py at main · doocs/leetcode

elder tusk
young sand
fallow lance
#

Oh nice!

rare niche
#

That's great! Thank you all, guys.

naive wolf
#

Hello folks. I am curious that if there are some issues when I use Black with pre-commit to configure options via pyproject.toml file.

I use Python 3.11, pre-commit 3.3.1, and Black 23.3.0. I run the below codes and command on MacOS Ventura 13.4.
I install packages in .venv directory created by poetry.toml file.

The below one is my pyproject.toml file.

[tool.black]
line-length = 120
target-version = ["py311"]

The below one is my .pre-commit-config.yaml file.

-   repo: https://github.com/psf/black
    rev: 23.3.0
    hooks:
    -   id: black

I run pre-commit command with poetry because I manage my packages with it. Thus, I create a command to run lint with Makefile file like the one below.

.PHONY: lint
lint:
    poetry run pre-commit install && poetry run pre-commit run

The pyrpoject.toml , .pre-commit-config.yaml , and Makefile exist in the same depth of directory. It looks like the one below.

├── .venv
├── Makefile
├── poetry.lock
├── poetry.toml
├── pyproject.toml
├── .pre-commit-config.yaml
└── src

When I run make lint command, Black fixes line length even it is not over 120. Can I get any help?

flat krakenBOT
#

Describe the bug

Black crashes when run on some code that includes a multiline statement with #type: ignore comments on multiple lines.

To Reproduce

For example, take this code:

class Foo:
   def foo(self) -> None:
       if True:
           self.foooooo= (  # type:ignore[error-code]
               Baaaaaaar(  # type:ignore[error-code]
                   self.baz()
               )
           ) 

And run it with these arguments:

$ black file.py

The resu...

flat krakenBOT
flat krakenBOT
flat krakenBOT
graceful trout
#

slick move right there with the zero. I too believe zero should always be put on a new line. It's too special not to be.. 🤦‍♀️

ivory quest
graceful trout
# ivory quest you can always increase or decrease line length setting

that wouldn't really help much tho. The default length is ok, mostly. But it'd be better if there was some checking of the length of elements. As far as I remember, a list gets expanded if it doesn't fit within the max line length, but.. cmon, 1 element with a total of 3 extra characters? Couldn't it like, check the amount of elements in the lists, and not do that if you're barely over the limit and resulting in 2 extra lines with 1-2 characters only? That doesn't seem like a difficult "fix", and would look a lot better in.. pretty much any case I can think of. Basically, to have a range as the limit, with a strict and soft limit, not just a strict limit..

#

And even if for some reason doing that is impossible.. why couldn't it just do this instead.. looks a lot better 💀

little parrot
#

you can do that yourself if you add a trailing comma right?

graceful trout
graceful trout
little parrot
#

can you paste the code?

graceful trout
# little parrot can you paste the code?

best to @ me, chances are I won't see the message otherwise:

test_data["Fare"].fillna(
    train_data.groupby(["Pclass", "Embarked", "Parch", "SibSp"]).Fare.mean()[3]["S"][0][
        0
    ],
    inplace=True,
)
little parrot
#

lol ok yeah doesnt matter

flat krakenBOT
#

Description

Fix #3737

Analysis of this issue:

Black has no problem parsing multiline consecutive magical comments like type: ignore, it works fine with these examples:

print(   "111") # type:ignore
print(   "111"                         ) # type:ignore
print(   "111"       ) # type:ignore

But Black encountered issue when parsing multiline open-parenthesis consecutive magical comments, code like this will cause Black to produce an `INTERNAL ERROR: ...

flat krakenBOT
#

Describe the bug

black formats the following code improperly handling # Trailing same-block.

x = 1
# Leading comment
del (
    # First inner own-line
    x  # Trailing comment same-line
    # Trailing comment own-line last inner
)  # Trailing same-block
# Trailing own-line

Result

@@ -4,5 +4,6 @@ del (
     # First inner own-line
     x  # Trailing comment same-line
     # Trailing comment own-line last inner
-)  # Trailing same-block
-# T...
elder tusk
#

hmm

#

today i discover that now black is hanging very often

#

py-spy tells me:

    __enter__ (multiprocessing/synchronize.py:95)
    get (multiprocessing/queues.py:102)
    _process_worker (concurrent/futures/process.py:237)
    run (multiprocessing/process.py:108)
    _bootstrap (multiprocessing/process.py:315)
    _launch (multiprocessing/popen_fork.py:71)
    __init__ (multiprocessing/popen_fork.py:19)
    _Popen (multiprocessing/context.py:277)
    start (multiprocessing/process.py:121)
    _adjust_process_count (concurrent/futures/process.py:675)
    submit (concurrent/futures/process.py:697)
    run_in_executor (asyncio/base_events.py:814)
    <dictcomp> (black/concurrency.py:163)
    schedule_formatting (black/concurrency.py:161)
    _run (asyncio/events.py:80)
    _run_once (asyncio/base_events.py:1890)
    run_forever (asyncio/base_events.py:596)
    run_until_complete (asyncio/base_events.py:629)
    reformat_many (black/concurrency.py:108)
    new_func (click/decorators.py:26)
    invoke (click/core.py:760)
    invoke (click/core.py:1404)
    main (click/core.py:1055)
    __call__ (click/core.py:1130)
    <module> (black:8)
#

hmm but there are way more processes than i expect, another classic multiprocessing.cpucount() thing?

#

okay i'll patch that in and see if it helps. weird that it's only happening with mypyc...

#

oh but maybe the actual difference is some ci caching changes that work made

#

anyway, could be nice for --workers to be specifiable by env var as well. is that a patch you'd be willing to take?

dense jungle
#

why should --workers be special and deserve an env var?

elder tusk
#

it's not critical by any means, but feels weird to change our incantations to specify --workers=fixed_number when the fixed number only matters in CI. the assumption that local machines and CI have same number of cores doesn't really hold

dense jungle
#

an env var is a good fit in that case

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Describe the bug

Long strings and f-strings are not being formatted to line-width.
New strings created by black are not respecting line-width.

To Reproduce

For example, take this code for variable a:

a = f"{nested_ui_dict_val[i][j][k]['name']} ansible_host={nested_ui_dict_val[i][j][k]['mgmt_ip']} MYPORT=111222333 PATH={nested_ui_dict_val[i][j][k]['path']} ip={nested_ui_dict_val[i][j][k]['ip']} NODESTUFF={nested_ui_dict_val[i][j][k]['nodestuff']} MOREID={neste...
onyx current
#

Intresting

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
fallow lance
#

Does black have a special case for # type: ignore comments? After switching to pyright and # pyright: ignore comments people noticed that black is much more liberal with re-shuffling the comments which leads to frustrating cycle of fighting with it to keep the comments on the lines they intended to be on. Curious why we didn't notice it before.

dense jungle
fallow lance
#

Actually this seems different...

dense jungle
flat krakenBOT
flat krakenBOT
#

Describe the style change

In functions with the new type parameter syntax, the type parameter bracket should only be made multi-line if it itself does not fit on one line. (Sorry, this is best explained with an example; see below.)

Examples in the current Black style

def f[
    T
](a_long_param_name: list[T] | tuple[T, ...], another_long_param_name: T) -> list[T]:
    pass
def g[
    T
](
    a_long_param_name: list[T] | tuple[T, ...]...
stiff spear
#

Hi.

A question about how black uses pyproject.toml. We have a big repo with some nested pyproject.toml's. In this case black will pick the closest pyproject.toml file based on current directory while we would preferably like to specifiy our black config only in the root pyproject.toml file.

In contrast, ruff does exactly this and it works pretty weel for us https://github.com/astral-sh/ruff/blob/main/crates/ruff/src/settings/pyproject.rs#L48 It will check that there is actually a tools.ruff section before deciding to use a pyproject.toml file.

#

If this is something that seems reasonable I am willing to create a PR for it

flat krakenBOT
elder tusk
flat krakenBOT
rancid abyss
#

anyone aware of a pseudo-repr function thats able to render strings or tuples in a black safe manner - i'd like the setuptools_scm python version file template to yield black safe code, without having to sort out details like line length or quoting myself - my impression is that the alternative would need to have black format it and i'd like ot avoid that

slow ibex
#

Wdym by "black safe"?
String that is already formatted in black-like style (so applying black to it does nothing)?

flat krakenBOT
#

Describe the bug

Given the following configuration in pyproject.toml

[tool.black]
line-length = 120
extend-exclude = [
    '^(?:([^\/]+\/)+(?:test_.*\.py|.*_test\.py))$',
    '.github',
    '.mypy_cache',
    '.pytest_cache',
    'venv'
]

Black fails with the error:

Error: Invalid value for '--extend-exclude': Not a valid regular expression: unbalanced parenthesis at position 17

But this is a valid regex that supposed to match any files starting ...

flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
flat krakenBOT
#

Hello,

I seem to have found a bug in black's preview style regarding assignment expressions, that has been present since version 23.1.0.

Describe the bug

When using an assignment expression in my code example, black with preview=true complains it cannot parse the line. Black preview=false accepts the code happily and leaves no changes.

To Reproduce

Here's my code example:

# file.py
from pydriller import Commit

commits: list[Commit] = []
update_hashes...
late dewBOT
#

:incoming_envelope: :ok_hand: applied timeout to @pliant fossil until <t:1688324939:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

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

flat krakenBOT
#

Description

Relates to #3708 by deleting the .black.env folder specified by ENV_PATH on action completion.

I had a difficult time replicating the issue above @JelleZijlstra and I can't see that any changes were made to stable that would effect this behaviour. Probably worth deleting that .black.env dir anyway?

Checklist - did you ...

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

Describe the bug

ERROR: Could not find a version that satisfies the requirement hatchling>=1.8.0 (from versions: none)

To Reproduce

on black installation

For example, take this code:

this = "code"

And run it with these arguments:

$ black file.py --target-version py39

The resulting error is:

cannot format file.py: INTERNAL ERROR: ...

Expected behavior

Environment

  • Black's version:
  • OS and Python...
flat krakenBOT
bright glacier
#

@elder tusk you've beat two maintainers in issue closures in like a week 😄

#

next target: Cooper