astral-sh/ruff · error
Expected statement to be embedded in a function definition
Error message
Expected statement to be embedded in a function definition
What it means
An anyhow bail! in the PT018 composite-condition fixer: after re-parsing the reconstructed module, the expected wrapping function definition was not found, so the rewritten assert statement cannot be extracted. The fix is abandoned rather than emitting broken code.
Solutions
- Verify the module reconstruction logic that embeds the statement in a function
- Skip the fix when the re-parsed tree does not have the expected shape
Defensive patterns
Strategy: try-catch
When it happens
Trigger: Thrown at crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs:759 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of astral-sh/ruff@26f38c119c (2026-09-05).
Data as JSON: /api/errors/6f047dd8afb4e2ec.
Report an issue: GitHub.
Appendix: source
Thrown at crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs:759
let module_text = if outer_indent.is_empty() {
Cow::Borrowed(contents)
} else {
Cow::Owned(format!(
"def f():{}{contents}",
stylist.line_ending().as_str()
))
};
// Parse the CST.
let mut tree = match_module(&module_text)?;
// Extract the assert statement.
let statements = if outer_indent.is_empty() {
&mut tree.body
} else {
let [Statement::Compound(CompoundStatement::FunctionDef(embedding))] = &mut *tree.body
else {
bail!("Expected statement to be embedded in a function definition")
};
let indented_block = match_indented_block(&mut embedding.body)?;
indented_block.indent = Some(outer_indent);
&mut indented_block.body
};
let [Statement::Simple(simple_statement_line)] = statements.as_slice() else {
bail!("Expected one simple statement")
};
let [SmallStatement::Assert(assert_statement)] = simple_statement_line.body.as_slice() else {
bail!("Expected simple statement to be an assert")
};
// Extract the individual conditions.
let mut conditions: Vec<Expression> = Vec::with_capacity(2);View on GitHub (pinned to 26f38c119c)