How can I do a conditional yield with Python?

I have to refactor some code. The original code was something like:

 while (yield _requires_payment(state)):
        did_pass_limit = yield _did_pass_limit(state)
        if not did_pass_limit:
            if existing_count is None:
                yield send_info_log("some stuff")
            yield send_info_log(f"more stuff")

So I refactored to:

    if yield _requires_payment(state):
        yield send_info_log(f"stuff")

If it matters, the function definition is:

async def _requires_payment(state):
    return await apply_payment_status_check(state, check_types=["window"])

But this creates an issue. What am I doing wrong?

>Solution :

If you want to use yield as an expression, surround it with parentheses. Just like it was in your while condition.

Leave a Reply