Skip to content

Commit

Permalink
Avoid asyncio-dangling-task for nonlocal and global bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Dec 23, 2023
1 parent 20def33 commit c7e9f2a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 10 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF006.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,13 @@ async def f(x: bool):
t = asyncio.create_task(asyncio.sleep(1))
else:
t = None


# OK
async def f(x: bool):
global T

if x:
T = asyncio.create_task(asyncio.sleep(1))
else:
T = None
16 changes: 13 additions & 3 deletions crates/ruff_linter/src/rules/ruff/rules/asyncio_dangling_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,15 @@ pub(crate) fn asyncio_dangling_binding(
for binding_id in scope.binding_ids() {
// If the binding itself is used, or it's not an assignment, skip it.
let binding = semantic.binding(binding_id);
if binding.is_used() || !binding.kind.is_assignment() {
if binding.is_used()
|| binding.is_global()
|| binding.is_nonlocal()
|| !binding.kind.is_assignment()
{
continue;
}

// Otherwise, any dangling tasks, including those that are shadowed, as in:
// Otherwise, flag any dangling tasks, including those that are shadowed, as in:
// ```python
// if x > 0:
// task = asyncio.create_task(make_request())
Expand All @@ -127,10 +131,16 @@ pub(crate) fn asyncio_dangling_binding(
std::iter::successors(Some(binding_id), |id| semantic.shadowed_binding(*id))
{
let binding = semantic.binding(binding_id);
if binding.is_used() || !binding.kind.is_assignment() {
if binding.is_used()
|| binding.is_global()
|| binding.is_nonlocal()
|| !binding.kind.is_assignment()
{
continue;
}

println!("binding: {:?}", binding);

let Some(source) = binding.source else {
continue;
};
Expand Down

0 comments on commit c7e9f2a

Please sign in to comment.