Skip to content

Incorrect SyntaxError attributes when raised by compile #127927

Open

Description

@mrigankpawagi

Bug report

Bug description:

This is probably a problem with compile, and I will demonstrate it through ast.parse. Consider the following code in a file f.py.

import ast

code = "x y"
ast.parse(code, filename='f.py')

This correctly raises a SyntaxError with lineno = 1 and offset = 3 since the error is at the beginning of y in the code. However, the traceback points into the file f.py itself, instead of the string code. Notice that it points to the third column of the first line of f.py.

  File "f.py", line 1
    import ast
      ^
SyntaxError: invalid syntax

This does not happen for any other string given as filename to ast.parse. In general, the traceback seems to point with the "correct" lineno and offset to the code in the file itself instead of code given to ast.parse. However, the problem is slightly more nuanced. If the offset in the string given to ast.parse is more than the length of the corresponding line in f.py, the offset attribute of the SyntaxError raised is incorrectly set to the length of the corresponding line in f.py plus two. Consider the following code in f.py.

import ast

code = "                                     x y"
ast.parse(code, filename='f.py')

This raises the following exception.

  File "f.py", line 1
    import ast
              ^
IndentationError: unexpected indent

On closer inspection, it turns out that the offset of the exception raised is 12 (note that the length of "import ast" is 10) instead of the correct 37 which is observed when filename is set to anything other than f.py. However, something more interesting happens when the number of lines in the code string is more than the number of lines in the file f.py.

import ast

code = "\n\n\n\nx y"
ast.parse(code, filename='f.py')

The problem goes away!

  File "f.py", line 5
    x y
      ^
SyntaxError: invalid syntax

We even see the correct offset.

CPython versions tested on:

3.11, 3.12, 3.13

Operating systems tested on:

Linux

(Edit) Incorrect text attribute

There is something more going on here. The following issue can be seen in 3.11 and 3.12 but not in 3.13. Consider the following f.py.

import ast

with open('temp.py') as f:
    code = f.read()
ast.parse(code, filename='temp.py')

temp.py is as follows.

"""                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             """; x """                                                                                                                                                         """; foobar

This leads to the following traceback.

  File "temp.py", line 1
    foobar
          ^
SyntaxError: invalid syntax

Besides the fact that the offset is incorrectly set to 8 (instead of 840), the text is incorrectly set to foobar (on 3.13, the entire file contents of temp.py are present in text). This problem goes away if filename is set to anything else. The problem also goes away if the contents of temp.py are shorter!

Linked PRs

Activity

  1. added
    type-bug
    on Dec 13, 2024
  2. changed the title [-]Incorrect SyntaxError attributes[/-] [+]Incorrect SyntaxError attributes when raised by `compile`[/+] on Dec 13, 2024
  3. added
    interpreter-core
    on Dec 13, 2024
  4. terryjreedy commented on Dec 13, 2024

    @terryjreedy
    Member

    In general, exceptions include a 'traceback' object which constitutes a linked list of stack frames. The only connection from stackframe to source is a file name. An exception not caught by code is caught by the Python runtime, which prints a default traceback display. The traceback printer uses filenames to get source lines when available.

    Your example mis-represents the content of file.py. Mis-information in, mis-information out. We could close as "won't fix".

    Could we do better? SyntaxErrors include a .text attribute. Could the default traceback printer ignore the filename when attempting to retrieve the error source line and get e.text instead? Could this simplify any of the current workarounds for getting SyntaxError source lines?

  5. mrigankpawagi commented on Dec 13, 2024

    @mrigankpawagi
    Author

    Thanks for your comment, @terryjreedy. Please correct me here: since I set filename='f.py', the traceback printer reads f.py and supplies that source to the exception's text field. How does the string code return after the end of f.py in the case where I added newlines?

    The documentation has little information on what filename does (from what I can see, it says that filename should have the name of the source of the code — this will make traceback easier to understand).

  6. mrigankpawagi commented on Dec 13, 2024

    @mrigankpawagi
    Author

    Also even if the traceback shows mis-information, it is not immediately clear to me why sometimes the offset value is incorrect.

  7. picnixz commented on Dec 13, 2024

    @picnixz
    Member

    IIRC, the "filename" is not the name of the file containing the compile call but the "file" that contains the code being compiled. In your case, the code that is being compiled is "x y" (there is no "file" in this case). As you observed, changing the name of the file makes it work.

    Now, if you use a filename that exists and that has been somehow cached by linecache, I think you'll also get an incorrect traceback report (but I didn't check this).

  8. added
    pending
    on Dec 13, 2024
  9. mrigankpawagi commented on Dec 13, 2024

    @mrigankpawagi
    Author

    I see. I understand the misinformation in, misinformation out argument, but I think that even if the traceback is not right, the exception object should provide correct offset values. This information has downstream effects, for example, in code quality tools like pyflakes.

  10. mrigankpawagi commented on Dec 13, 2024

    @mrigankpawagi
    Author

    @picnixz @terryjreedy I have updated the issue with the following additions. Again, your insights will be very helpful.

    Incorrect text attribute

    There is something more going on here. The following issue can be seen in 3.11 and 3.12 but not in 3.13. Consider the following f.py.

    import ast
    
    with open('temp.py') as f:
        code = f.read()
    ast.parse(code, filename='temp.py')

    temp.py is as follows.

    """                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             """; x """                                                                                                                                                         """; foobar

    This leads to the following traceback.

      File "temp.py", line 1
        foobar
              ^
    SyntaxError: invalid syntax
    

    Besides the fact that the offset is incorrectly set to 8 (instead of 840), the text is incorrectly set to foobar (on 3.13, the entire file contents of temp.py are present in text). This problem goes away if filename is set to anything else. The problem also goes away if the contents of temp.py are shorter (by at least 8 characters)!

    I am not sure if this is also misinformation (after all the code really is from temp.py) — and the fact that this is fixed in 3.13 is also very interesting... I find this behaviour very unexpected particularly because it comes up only for long strings.

  11. picnixz commented on Dec 14, 2024

    @picnixz
    Member

    Let's start with something simple. Assume that we have:

    """..."""; x """..."""; foobar

    Besides the fact that the offset is incorrectly set to 8 (instead of 840), the text is incorrectly set to foobar (on 3.13, the entire file contents of temp.py are present in text).

    Now, it appears that the offset entirely depends on the filename that is being passed, which is something I find a bit surprising though. So I can try to investigate. For instance, on 3.11.3 (Windows), in the REPL:

    import ast
    
    code = '"""..."""; x """abc"""; foobar'
    
    try:
    	ast.parse(code)
    except SyntaxError as e:
    	assert e.offset == 14

    versus:

    import ast
    import fnmatch
    
    code = '"""..."""; x """..."""; foobar'
    
    try:
    	ast.parse(code, filename=fnmatch.__file__)
    except SyntaxError as e:
    	assert e.offset == 14

    Both report the message identitically. In the first case, it's """..."""; x ["""abc"""]; foobar being highlighted while in the second it's """Filename m[atching w]ith shell patterns. (this is the first docstring of fnmatch.py) (the part with ^^^^^ below is in brackets).

    Now, I tried replacing my ... with 800 whitespaces and the offset changed to 811 in the first case (which is what expected) and 43 in the second case (which is not what I expected). Note that 43 in this case is the minimum between the line length of the reported error (first line """Filename matching with shell patterns. of fnmatch.__doc__ has 43 characters) and the actual "error" that we obtained without the filename (so min(43, 811) = 43 I think). Now, in 3.13+, we might perhaps not compute that minimum anymore, but I don't have access to a machine for testing this now.

    @pablogsal @JelleZijlstra can you confirm the analysis? or say something on this topic.


    The fact that this is fixed in 3.13 is also very interesting

    If you can, can you bisect the commit for that? if not I have some guesses:

    • It was fixed because of the new REPL.
    • It was fixed because we fixed something in the AST. Or because how we parse stuff.
    • It was fixed because we fixed linecache recently (I know we fixed something but I don't know if it could have helped).
    • Did we change tokenization in some way that made it behave differently? and report offsets differently?
  12. removed
    pending
    on Dec 14, 2024
  13. picnixz commented on Dec 14, 2024

    @picnixz
    Member

    I'm removing the pending label because I would like to know whether it's really an issue or not and whether 3.12 should or can be fixed.

  14. mrigankpawagi commented on Dec 15, 2024

    @mrigankpawagi
    Author

    Thanks for the analysis, @picnixz. I will try to look into the commits and share on this thread if I find something.

    In my example, I set filename to the actual temp.py (in your example, you point to a different file altogether) which does contain the same number of characters on its first line (after all the code is from that very file itself). Your guess regarding the minimum may not directly explain this. What do you think?

  15. picnixz commented on Dec 15, 2024

    @picnixz
    Member

    On Python 3.9, I also have an offset of 14 (or 808 depending on the number of whitespaces I put) when I use the real filename. When I use the fake filename (fnmatch.__file__), I get 808 on Python 3.9 but 43 on Python 3.12. So something is happening indeed.

  16. mrigankpawagi commented on Dec 15, 2024

    @mrigankpawagi
    Author

    Thanks for checking with 3.9. Yes, interesting indeed!

  17. saggl commented on Nov 30, 2026

    @saggl

    @picnixz, the change in the temp.py example landed in 3.12.7 and 3.13.1. I used Codex to run the version comparisons on Linux and inspect the attributes on the caught SyntaxError.

    For the reporter’s 1,006-byte line with no final newline, 3.12.6 and 3.13.0 return exc.text == " foobar" and exc.offset == 8. The file reader kept the last seven bytes of the line, so the offset was capped at 8. On 3.12.7 and 3.13.1 it keeps the first 999 bytes, which includes the start of the second string literal at column 840. Building the original change and both backports against their immediate parents reproduced the switch from 8 to 840 in all three pairs. Original change · 3.12 backport · 3.13 backport

    For the fnmatch.__file__ example, the first line of fnmatch.py has 42 characters including its newline. During 3.10 development the parser first capped the column at the line length (42), then allowed one position past the end (43). On 3.9.21 the older conversion assumed the column fit the selected line. Measuring the parser column before file lookup gave 808 with 797 spaces and 811 with 800, for either filename. First cap · Change to allow one past the end

    One case still gives the wrong column when the filename and source agree. On main at 114f465, write "x" + " " * 1200 + "y" to a file and pass its contents and filename to ast.parse(). The y is at column 1202. The exception gives (offset, end_offset) == (1000, 1000), and its 999-character text ends before the y. Would a patch that reads the complete error line from regular files while keeping the existing filename lookup be welcome here?

  18. picnixz commented on Nov 30, 2026

    @picnixz
    Member

    I am not really interested in the version but in the commits bisection.. More importantly I rather prefer a core dev making that decision rather than just following whatever Codex suggests.

  19. saggl commented on Nov 30, 2026

    @saggl

    For the fnmatch.__file__ example you reported, I used Codex to run git bisect on the parser source. 123ff26 first capped the offset at the length of the displayed line. b86ed8e then allowed one position past the end. The line in fnmatch.py has 42 characters including its newline. Builds of those commits returned 42 and 43 respectively. First cap · One-past-the-end change

    For the reporter’s separate temp.py example, a source bisection found e2f7107. Running the example at each selected revision on the release branches identified its backports, 1854224 and 03ae82d. Both immediate parents gave offset 8, and both backports gave 840. Development commit · 3.12 backport · 3.13 backport

    I’ll leave the decision about whether to change the behavior to the core developers.

    Source bisection logs for the two column limits

    Capping at the line length

    git bisect start '--term-old=before' '--term-new=after' 'v3.10.0a7' 'v3.10.0a6'
    git bisect before 39f643614d03748a5fad462fe7ed26a174a522fa
    git bisect after 85b6b70589c187639aeebc560d67e9cc04abb4d8
    git bisect after b045cdaf341f80b7d1e4804b932b6e415600c2e1
    git bisect after a81fca6ec8e0f748f8eafa12fb12cf9e12df465c
    git bisect after 9feae41c4f04ca27fd2c865807a5caeb50bf4fc4
    git bisect after 532e063fc2bf9e6e80550670ddc5dc5d2b1d2450
    git bisect after 96eeff516204b7cc751103fa33dcc665e387846e
    git bisect after 123ff266cda9ad279106f20dca06ba114f6a9b8a
    # first after commit: [123ff266cda9ad279106f20dca06ba114f6a9b8a] bpo-43591: Fix error location in interactive mode for errors at the end of the line (GH-24973)
    

    Allowing one position past the end

    git bisect start '--term-old=before' '--term-new=after' 'v3.10.0b1' 'v3.10.0a7'
    git bisect after 702a0885ba3636959d4c176797814937c497b986
    git bisect after c2b7a66b91cdb96fbfdb160f96797208ddc5e436
    git bisect before 54366953633dbe5d9585dbae0c633d4e92df2d04
    git bisect before dfb45323ce8a543ca844c311e32c994ec9554c1b
    git bisect before 67c0b3d89c4da9750fdb43fc66d3924681b22d2e
    git bisect after a9cf69df2e031d6157f01289f66ca9cf723ceb5c
    git bisect after b86ed8e3bb41ede77eeab4a8bb4e2b91a8065283
    git bisect before 2459b92a4db69d9b14d0a86a9b81cc075894e910
    # first after commit: [b86ed8e3bb41ede77eeab4a8bb4e2b91a8065283] bpo-43797: Improve syntax error for invalid comparisons (#25317)
    
    Python 3.12 runtime bisection log
    git bisect start '--term-old=tail' '--term-new=prefix' 'v3.12.7' 'v3.12.6'
    git bisect tail d26d0a10b1314d75de73b22354af8288247db4ed
    git bisect prefix 69fd1f218c8b26f75aa230c9459f24fe05fdd784
    git bisect prefix 13565f15805c20d3aba42a123cdeeda91e67a603
    git bisect prefix 996e4094017f22660ad74f94d092f8ba2cc1675e
    git bisect tail 0e838b52fe323569138ac2f74979d99336067296
    git bisect prefix 18542240c26cea2b5e0372b668a5e67bd9015379
    git bisect tail 7e2d414a599782773f46eb8a20506db0cfa3dcce
    # first prefix commit: [18542240c26cea2b5e0372b668a5e67bd9015379] [3.12] gh-124188: Fix PyErr_ProgramTextObject() (GH-124189) (GH-124426)
    
    Python 3.13 runtime bisection log
    git bisect start '--term-old=tail' '--term-new=prefix' 'v3.13.1' 'v3.13.0'
    git bisect prefix 210bd2a50dddc10119c4f68329e9e683d2f82e0b
    git bisect prefix 8cf646adeab0e5a368cc2875068a725a324fc7c1
    git bisect prefix b6c17eb76f4e1b4e04341deb569c9d581f9a75e3
    git bisect prefix 6925e5b5c778d0c7deab58c62545b69b4a3d3844
    git bisect prefix 4a9a359f32d3f42c509bb9be770370ba21634fc6
    git bisect prefix 03ae82d0d34649d1fcb755015aa567fe3978d4f9
    git bisect tail 6fe746d702bfeeafbde1e9df2b1b5e061808fbb5
    git bisect tail 167d8d2f072505a85c6db72fdaf4edffd6d17f3a
    # first prefix commit: [03ae82d0d34649d1fcb755015aa567fe3978d4f9] [3.13] gh-124188: Fix PyErr_ProgramTextObject() (GH-124189) (GH-124423)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions