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

New rule: warning accidental garbage collection of asyncio.create_task #2809

Closed
Glyphack opened this issue Feb 12, 2023 · 5 comments · Fixed by #2935
Closed

New rule: warning accidental garbage collection of asyncio.create_task #2809

Glyphack opened this issue Feb 12, 2023 · 5 comments · Fixed by #2935
Labels
rule Implementing or modifying a lint rule

Comments

@Glyphack
Copy link
Contributor

I wanted to purpose a new lint rule. The asyncio.create_task function has a caveat, which is when you create a task in order to make sure it finishes you need to take a reference to it.
image

I first read about this in this post. Which also sites a lot of projects that are doing this wrong.

Is this something that ruff wants to support? I could give it a try to implement it in that case.

@edgarrmondragon
Copy link
Contributor

This was requested in flake8-async: Zac-HD/flake8-async-archive#5

@charliermarsh
Copy link
Member

We could implement it as part of RUF for now. I'd support it!

@charliermarsh charliermarsh added the rule Implementing or modifying a lint rule label Feb 12, 2023
@samuelcolvin
Copy link

amazing!

@charliermarsh
Copy link
Member

Lol, I can do this today, I didn't realize there were so many upvotes on it.

@Lunarmagpie
Copy link
Contributor

I didn't know I needed this lol

charliermarsh added a commit that referenced this issue Feb 15, 2023
#2935)

This rule guards against `asyncio.create_task` usages of the form:

```py
asyncio.create_task(coordinator.ws_connect())  # Error
```

...which can lead to unexpected bugs due to the lack of a strong reference to the created task. See Will McGugan's blog post for reference: https://textual.textualize.io/blog/2023/02/11/the-heisenbug-lurking-in-your-async-code/.

Note that we can't detect issues like:

```py
def f():
    # Stored as `task`, but never used...
    task = asyncio.create_task(coordinator.ws_connect())
```

So that would be a false negative. But this catches the common case of failing to assign the task in any way.

Closes #2809.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants