Skip to content

fix: handle async with/def/for + semicolon + # fmt: skip crash (issue #5307) - #5314

Closed
HosnainRafi wants to merge 1 commit into
psf:mainfrom
HosnainRafi:fix/5307-async-semicolon-fmt-skip
Closed

HosnainRafi wants to merge 1 commit into
psf:mainfrom
HosnainRafi:fix/5307-async-semicolon-fmt-skip

Conversation

@HosnainRafi

Copy link
Copy Markdown

Summary

Black crashes with a ParseError when formatting a one-line async with or async def statement that has a semicolon-separated body and a # fmt: skip comment:

async with give_me_async_context(): print("a");  # fmt: skip
async def give_me_async_context(): print("a");  # fmt: skip

Root Cause

The # fmt: skip handling in comments.py preserves the entire compound statement header inline when the body contains semicolons. However, for async statements, the ASYNC token is a sibling of the compound statement inside the async_stmt wrapper node — it is not a child of the with_stmt/funcdef. This means the header collection logic in _get_compound_statement_header was missing the async keyword, causing Black to split it onto its own line during the first pass. On the second pass, async alone on a line is not valid Python, resulting in a parse error.

Fix

  1. In _get_compound_statement_header: when the compound statement's parent is an async_stmt, also include the ASYNC token in the header leaves.

  2. In _find_compound_statement_context: added a new Case 3 to handle the async_stmt wrapper structure (async_stmt -> compound_stmt -> simple_stmt).

Tests

  • Added regression test cases to tests/data/cases/fmtskip10.py for async def and async with with semicolon bodies and # fmt: skip.
  • All 398 existing tests pass.

When a one-line async with/def/for statement has a semicolon-separated
body and a `# fmt: skip` comment, Black crashes because the ASYNC token
is not included in the ignored nodes. The ASYNC token is a sibling of
the compound statement (inside async_stmt), not a child, so it was
being excluded from the header preservation logic.

This fix ensures that when a compound statement is wrapped in an
async_stmt, the ASYNC token is included in the header leaves so the
entire statement is preserved inline.

Fixes psf#5307
@github-actions

Copy link
Copy Markdown
Contributor

diff-shades results comparing this PR (45781ce) to main (74371e2):

--preview style: no changes

--stable style: no changes


What is this? | Workflow run | diff-shades documentation

@cobaltt7

Copy link
Copy Markdown
Collaborator

Thanks! Sorry, but I ended up going with #5311 due to the more concise and targeted fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants