Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SIM115] Allow open followed by close #7916

Merged
merged 4 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,7 @@
with contextlib.ExitStack() as exit_stack:
exit_stack_ = exit_stack
f = exit_stack_.enter_context(open("filename"))

# OK
open("filename").close()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment why this combination is needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
open("filename").close()
# OK (file is closed immdeidately)
open("filename").close()

comment like this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More like "Used to clear an existing file (https://stackoverflow.com/a/2769090/3549270)"

There's Path.touch now but i'm surprised there's nothing similar from clearing a file.

pathlib.Path("foo.txt").open().close()
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,34 @@ fn is_open(checker: &mut Checker, func: &Expr) -> bool {
}
}

/// Return `true` if the current expression is followed by a `close` call.
fn is_closed(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_grandparent() else {
return false;
};

let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};

let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
return false;
};

attr.as_str() == "close"
}

/// SIM115
pub(crate) fn open_file_with_context_handler(checker: &mut Checker, func: &Expr) {
if !is_open(checker, func) {
return;
}

// Ex) `open("foo.txt").close()`
if is_closed(checker.semantic()) {
return;
}

// Ex) `with open("foo.txt") as f: ...`
if checker.semantic().current_statement().is_with_stmt() {
return;
Expand Down
Loading