MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
187 stars 19 forks source link

yield from is not allowed in async function #146

Closed wyuenho closed 2 years ago

wyuenho commented 2 years ago

Desired change

Do not warning if a SIM104 is encountered inside an async function or method.

Explanation

Why is the adjustment necessary / better?

The suggested fix to replace a for yield loop with a yield from statement is invalid inside an async function.

Example

This is an example where the mentioned rule(s) would currently be suboptimal:

async fib(limit=10):
    if limit == 1:
        yield 0
    if limit == 2:
        yield 0
        yield 1
    i, j = 0, 1
    for _ in range(2, limit):
        n = i + j
        yield n
        i, j = j, n
MartinThoma commented 2 years ago

Looks like a duplicate of https://github.com/MartinThoma/flake8-simplify/issues/67 . Which version of flake8-simplify do you use?

wyuenho commented 2 years ago

I'm on 0.19.2

wyuenho commented 2 years ago

Looks like the ast.For node doesn't have a parent attribute and you've ignore type checking on that line so you didn't catch this? How does flake8 handle exceptions thrown from a rule?

wyuenho commented 2 years ago

Ah I see, the AST appears to be an astor tree. In that case I guess this rule is failing in my code is because

def foo():
    with open('/some/file') as f:
        for line in f:
            yield line

The parent of the for loop is a with block, not an async function.