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

UP028 for multiple loops does not work #13266

Closed
spaceby opened this issue Sep 6, 2024 · 2 comments · Fixed by #13504
Closed

UP028 for multiple loops does not work #13266

spaceby opened this issue Sep 6, 2024 · 2 comments · Fixed by #13504
Labels
bug Something isn't working rule Implementing or modifying a lint rule

Comments

@spaceby
Copy link

spaceby commented Sep 6, 2024

UP028 does not work when there are multiple yield loops in a function

Code example:

def text_not_ok():
    a = [1, 2, 3]
    for photo in a:
        yield photo
    for photo in a:
        yield photo

https://play.ruff.rs/b9748aaf-8e8c-45cd-8138-20f41013b979

@AlexWaygood
Copy link
Member

I think this is because of this logic here:

// If any of the bound names are used outside of the yield itself, don't rewrite.
if collect_names(value).any(|name| {
checker
.semantic()
.current_scope()
.get_all(name.id.as_str())
.any(|binding_id| {
let binding = checker.semantic().binding(binding_id);
binding.references.iter().any(|reference_id| {
checker.semantic().reference(*reference_id).range() != name.range()
})
})
}) {
return;
}

I.e., Ruff believes that some of the variables bound by the first loop might be referenced in the second loop, so it comes to the conclusion that it won't necessarily be safe to rewrite them as yield from statements. If you change the second loop to use different variable names, it flags both loops with UP028: https://play.ruff.rs/50ee023e-60f4-4a77-a870-3378a6c68b72

It would be possible to improve Ruff's behaviour here, I think, but it might add some complexity to our implementation

@MichaReiser MichaReiser added the rule Implementing or modifying a lint rule label Sep 7, 2024
@spaceby
Copy link
Author

spaceby commented Sep 17, 2024

Then you need to improve ruff's behavior
Or add another rule that tracks repeating loops
Or add a warning about this behavior to the documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants