psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
37.6k stars 2.38k forks source link

Black Formatter not working for this code. #4354

Closed finntenzor closed 3 weeks ago

finntenzor commented 3 weeks ago

Can not format this code

class Or:
    def __init__(self, rs) -> None:
        self.rs = rs

    def __str__(self):
        return f'Or({','.join(self.rs)})'

    def __repr__(self) -> str:
        return str(self)
  1. Update Black's version if a newer release exists: pip install -U black Already updated
  2. Use the online formatter at https://black.vercel.app/?version=main Still can not format

To Reproduce

Copy these code to a file, and format it by VSCode.

Run arguments:

I don't known. I use this plugin in VSCode.

The resulting error is:

2024-05-09 17:13:40.556 [info] error: cannot format d:\ResearchProjects\DCompiler\demo.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: C:\Users\FINNTE~1\AppData\Local\Temp\blk_owfxifj1.log

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

log file content:

--- src
+++ dst
@@ -140,11 +140,11 @@
                                 value=
                                 Constant(
                                     kind=
                                     None,  # NoneType
                                     value=
-                                    ',',  # str
+                                    ', ',  # str
                                 )  # /Constant
                             )  # /Attribute
                             keywords=
                         )  # /Call
                     )  # /FormattedValue

Expected behavior

format success.

Environment

VSCode 1.89

Additional context

finntenzor commented 3 weeks ago

This seems to be due to the ambiguity of single quotes. The following code actually works fine in python.

f'Or({','.join(['1','2'])})'
JelleZijlstra commented 3 weeks ago

This is fixed in the most recent version of Black when running under Python 3.12. See https://github.com/psf/black/issues/4351#issuecomment-2098832514 for some related information.