Skip to content

ast.parse() inconsistency with type comments vs. type: ignore #131570

Open
@tusharsadhwani

Description

@tusharsadhwani

Bug report

Bug description:

Consider the following two code snippets:

with (x, y):
  pass

and:

with x, y:
  pass

They produce an identical AST, unless we try to parse type comments, in which case they deviate.


In case of a type COMMENT, we get DIFFERENT ASTs, with and without the brackets:

>>> import ast
>>> x = '''
... with (x, y): # type: int
...   pass
... '''
>>> y = '''
... with x, y: # type: int
...   pass
... '''
>>> print(ast.dump(ast.parse(x, type_comments=True), indent=2))
Module(
  body=[
    With(
      items=[
        withitem(
          context_expr=Tuple(
            elts=[
              Name(id='x', ctx=Load()),
              Name(id='y', ctx=Load())],
            ctx=Load()))],
      body=[
        Pass()],
      type_comment='int')],
  type_ignores=[])
>>> print(ast.dump(ast.parse(y, type_comments=True), indent=2))
Module(
  body=[
    With(
      items=[
        withitem(
          context_expr=Name(id='x', ctx=Load())),
        withitem(
          context_expr=Name(id='y', ctx=Load()))],
      body=[
        Pass()],
      type_comment='int')],
  type_ignores=[])

In case of type IGNORE, we get IDENTICAL ASTs with or without bracket:

>>> x = '''
... with (x, y): # type: ignore
...   pass
... '''
>>> y = '''
... with x, y: # type: ignore
...   pass
... '''
>>> print(ast.dump(ast.parse(x, type_comments=True), indent=2))
Module(
  body=[
    With(
      items=[
        withitem(
          context_expr=Name(id='x', ctx=Load())),
        withitem(
          context_expr=Name(id='y', ctx=Load()))],
      body=[
        Pass()])],
  type_ignores=[
    TypeIgnore(lineno=2, tag='')])
>>> print(ast.dump(ast.parse(y, type_comments=True), indent=2))
Module(
  body=[
    With(
      items=[
        withitem(
          context_expr=Name(id='x', ctx=Load())),
        withitem(
          context_expr=Name(id='y', ctx=Load()))],
      body=[
        Pass()])],
  type_ignores=[
    TypeIgnore(lineno=2, tag='')])

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.12only 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