black: Freeze/bad performance on escaped quotation in f-string

Describe the bug black hangs (or takes an extremely long time?) to process a file with a multiline f-string containing a bunch of escaped quotation marks.

To Reproduce Run black against this file:

def testing():
    somevar = "some value"
    return f"""
        {somevar} the following line causes the issue:
         \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" 
    """

Will just hang without any output.

Expected behavior Should run to completion within at most 1 second.

Environment

  • Black’s version: 24.10.0 (was working with 24.4.2, probably introduced in 24.8.0)
  • OS and Python version: macOS/Python 3.13.0

Additional context Extracting the quotes into a variable seems to circumvent the issue:

def testing():
    somevar = "some value"
    quotes = """\" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \""""
    return f"""
        {somevar} the following line causes the issue:
         {quotes} 
    """

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16

Most upvoted comments

I have a put up a rough version here:

https://github.com/tusharsadhwani/pytokens

This is a quick port from Zig to Python, and I may have made small errors. I’ll check tomorrow and try to throw it into Black.

Screenshot 2024-12-20 at 1 49 47 AM

Tokenizer parity is at 100%.

The plan for the fix right now is:

  • Change the Regex to get rid of the { at the end:

     # beginning of a single quoted f-string. must not end with `{{` or `\N{`
    -SingleLbrace = r"(?:\\N{|{{|\\'|[^\n'{])*(?<!\\N)({)(?!{)"
    -DoubleLbrace = r'(?:\\N{|{{|\\"|[^\n"{])*(?<!\\N)({)(?!{)'
    +SingleLbrace = r"(?:\\N{|{{|\\'|[^\n'{])*(?<!\\N)"
    +DoubleLbrace = r'(?:\\N{|{{|\\"|[^\n"{])*(?<!\\N)'
     
     # beginning of a triple quoted f-string. must not end with `{{` or `\N{`
    -Single3Lbrace = r"(?:\\N{|{{|\\'|'(?!'')|[^'{])*(?<!\\N){(?!{)"
    -Double3Lbrace = r'(?:\\N{|{{|\\"|"(?!"")|[^"{])*(?<!\\N){(?!{)'
    +Single3Lbrace = r"(?:\\N{|{{|\\'|'(?!'')|[^'{])*(?<!\\N)"
    +Double3Lbrace = r'(?:\\N{|{{|\\"|"(?!"")|[^"{])*(?<!\\N)'
    
  • Add a check wherever we use the token to find an FSTRING_MIDDLE, if the token is followed by a {{, to save some state and try to find the next possible match just after the {{ instead.

Alright. I’ll do a simple port and benchmark it over the weekend.