Python: Black doesn't wrap long lines
Asked Answered
A

3

35

I am using black==20.8b1.

I have a long string like:

return f"{self.name}, a {adjective.to_name()} {kin_string}{self._type.to_name()} who works for the {target.get_relationship_target_string()}."

I run:

$ black -l 80 . -t py38
All done! ✨ 🍰 ✨
2 files left unchanged.

Why is the string not wrapped? I thought that black supports wrapping strings now (based on issues in github).

Argol answered 31/8, 2020 at 3:47 Comment(0)
C
32

Use --preview option to trigger this behaviour.

Previously we had to add --experimental-string-processing option. This option still works but issues a depreciation warning.

I think in future versions it will be made default.

black -l 80 --preview file.py
Combat answered 9/11, 2020 at 8:28 Comment(2)
Looks like we have a new flag to replace --experimental-string-processing now: --preview. When running with --experimental-string-processing: <string>:12: Deprecated: experimental string processing` has been included in preview and deprecated. Use preview instead.` – Godfry
I now figured out that you need both --preview and --enable-unstable-feature=string_processing. I'm using black version 24.4.2. – Hagbut
A
19

Since 22.1.0 (Jan 29, 2022), you have to run Black with --preview.

Alit answered 3/5, 2022 at 21:36 Comment(2)
Thank you! This works for me when I do black --preview file.py. How can this work in VScode? I have included "python.formatting.blackArgs": [ "--preview" ] in my project's settings.json, but line wrapping is not enforced. – Montelongo
@Montelongo not really sure. These are my settings in VSCode: "python.formatting.provider": "black", "python.formatting.blackArgs": ["--preview"] (on MacOS). Looks like we have the same. It works for me. Does your VSCode succeed to format a file in Python (I mean, other than the line wrapping)? Maybe it can't find the Black binary on your system. – Alit
A
14

Currently, Black doesn't wrap long strings or long comments. You can see an open issue in their project GitHub saying:

Black currently doesn't wrap long string literals or merge string literals that happen to be on the same line. [...] It would require modifying the AST which isn't 100% safe and has a bunch of edge cases to be dealt with.

Amparoampelopsis answered 31/8, 2020 at 3:53 Comment(1)
Do you know why this issue is closed github.com/psf/black/issues/182 I thought it was already done? – Argol

© 2022 - 2024 β€” McMap. All rights reserved.