Skip to content

parser: cpython parser bug in template strings t'{0!=0:}' #146448

@15r10nk

Description

@15r10nk

Bug report

Bug description:

There is an bug in the parser for template strings when the expression contains a ! like in !=.
The value is parsed correct but the str attribute contains only the part before the !.

bug

>>> import ast

>>> print(ast.dump(ast.parse("t'{0!=0:}'"),indent=2))
Module(
  body=[
    Expr(
      value=TemplateStr(
        values=[
          Interpolation(
            value=Compare(
              left=Constant(value=0),
              ops=[
                NotEq()],
              comparators=[
                Constant(value=0)]),
            str='0',                # <- this should be 0!=0
            conversion=-1,
            format_spec=JoinedStr())]))])
>>> print(ast.dump(ast.parse("t'{0!=0:s}'"),indent=2))
Module(
  body=[
    Expr(
      value=TemplateStr(
        values=[
          Interpolation(
            value=Compare(
              left=Constant(value=0),
              ops=[
                NotEq()],
              comparators=[
                Constant(value=0)]),
            str='0',                    # <- same here
            conversion=-1,
            format_spec=JoinedStr(
              values=[
                Constant(value='s')]))]))])


correct

>>> import ast

>>> print(ast.dump(ast.parse("t'{0!=0}'"),indent=2))
Module(
  body=[
    Expr(
      value=TemplateStr(
        values=[
          Interpolation(
            value=Compare(
              left=Constant(value=0),
              ops=[
                NotEq()],
              comparators=[
                Constant(value=0)]),
            str='0!=0',
            conversion=-1)]))])
>>> print(ast.dump(ast.parse("t'{0==0:}'"),indent=2))
Module(
  body=[
    Expr(
      value=TemplateStr(
        values=[
          Interpolation(
            value=Compare(
              left=Constant(value=0),
              ops=[
                Eq()],
              comparators=[
                Constant(value=0)]),
            str='0==0',
            conversion=-1,
            format_spec=JoinedStr())]))])

I must also share the credit with Claude, who is currently in charge of developing pysource-codegen.

Image

CPython versions tested on:

3.14, 3.15

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixes3.15new features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-parsertype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions