[ruff] Implement post-init-default (RUF033)#13192
[ruff] Implement post-init-default (RUF033)#13192AlexWaygood merged 10 commits intoastral-sh:mainfrom
ruff] Implement post-init-default (RUF033)#13192Conversation
|
AlexWaygood
left a comment
There was a problem hiding this comment.
Sorry for reviewing a draft PR... couldn't resist! Looks great.
Co-authored-by: Alex Waygood <[email protected]>
Co-authored-by: Alex Waygood <[email protected]>
Co-authored-by: Alex Waygood <[email protected]>
Co-authored-by: Alex Waygood <[email protected]>
CodSpeed Performance ReportMerging #13192 will improve performances by 5.89%Comparing Summary
Benchmarks breakdown
|
RUF033)ruff] Implement post-init-default (RUF033)
AlexWaygood
left a comment
There was a problem hiding this comment.
Thanks! I pushed a couple of simplifications, but this was overall an excellent PR
| } | ||
|
|
||
| /// RUF033 | ||
| pub(crate) fn post_init_default(checker: &mut Checker, function_def: &ast::StmtFunctionDef) { |
There was a problem hiding this comment.
I made this run on StmtFunctionDef nodes rather than StmtClassDef nodes, as this allows us to access checker.semantic().current_scope() to see what other symbols have been bound in the class. This enables us to see much more simply and more accurately whether it's safe to add a new InitVar field to the class body in the fix
| let initvar_edit = Edit::insertion( | ||
| content.into_owned(), | ||
| locator.line_start(post_init_def.start()), | ||
| ); |
There was a problem hiding this comment.
Rather than iterate through all statements in the class body until we get the first non-docstring statement, I changed it so that we just insert the InitVar symbol in the line before the __post_init__ definition. It seems much simpler and less error-prone as we already know that we're past the docstring in this case
Summary
Implements the post-init-default (
RUF033) rule, which reports a diagnostic upon any__post_init__method with argument default. Has a sometimes available unsafe autofix. For example,from dataclasses import InitVar, dataclass @dataclass class Foo: """A very helpful docstring.""" + baz: InitVar[str] = "something" bar: InitVar[int] = 1 - def __post_init__(self, bar: int, baz: str = "something") -> None: ... + def __post_init__(self, bar: int, baz: str) -> None: ...Closes #13128
Test Plan
cargo nextest run