简体   繁体   English

如何使用 Python 进行条件收益?

[英]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:如果重要的话,函数定义是:

@dialog(version="1.0")
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?我究竟做错了什么?

If you want to use yield as an expression there, surround it with parentheses .如果你想在那里使用yield作为表达式, 用括号括起来 Just like it was in your while condition.就像它在你的while条件下一样。

(In assignment statements , like x = yield y , it's not needed, because that directly uses yield_expression instead of yield_atom .) (在赋值语句中,例如x = yield y ,不需要它,因为它直接使用yield_expression而不是yield_atom 。)

if evaluates Boolean values Try: if评估布尔值尝试:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM