Skip to content

Update line break heuristic when f-string has conversion flag #10042

@dhruvmanila

Description

@dhruvmanila

It seems that the following is an invalid syntax for pre 3.12 even for triple-quoted f-strings:

f"""fooooooooooooooooooooooooo barrrrrrrrrrrrrrrrrrrrrrrrrr {
    xxxxxxx!s
} aaaaaaaaaaaaaaaaaaaaaa"""
$ python3.11 -m ast main.py
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/Users/dhruv/.pyenv/versions/3.11.7/lib/python3.11/ast.py", line 1752, in <module>
    main()
  File "/Users/dhruv/.pyenv/versions/3.11.7/lib/python3.11/ast.py", line 1748, in main
    tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/dhruv/.pyenv/versions/3.11.7/lib/python3.11/ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 5
    } aaaaaaaaaaaaaaaaaaaaaa"""
                               ^
SyntaxError: f-string: expecting '}'

But, it's fine without the conversion flag:

f"""fooooooooooooooooooooooooo barrrrrrrrrrrrrrrrrrrrrrrrrr {
    xxxxxxx
} aaaaaaaaaaaaaaaaaaaaaa"""

The heuristic needs to be updated such that if a conversion flag is present, then we can add line breaks only if it's Python 3.12 or later. Care needs to be taken with the fact that in certain scenarios we assume that the target version is 3.12 even if it's not provided. This is when there's a multiline expression in a single-quoted f-string or a comment.

The same question applies here as mentioned in #10040 (refer to "Local or Global?" section).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingformatterRelated to the formatterpreviewRelated to preview mode features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions