是否可以延迟对作为函数调用一部分的表达式的求值?

问题描述 投票:2回答:1

在我的程序中,我多次出现这种模式:

if some_bool:
   print(f"some {difficult()} string")

我考虑过为此创建函数:

def print_cond(a_bool, a_string):
   if a_bool:
      print(a_string)

print_cond(some_bool, f"some {difficult()} string")

但是这样做的结果是,即使some_bool == False,也总是对第二个参数求值。是否有办法将对f字符串的评估延迟到实际打印出来为止?

python function lazy-evaluation
1个回答
0
投票

您可以通过将f字符串放在lambda中来延迟对其的求值。

例如:

def difficult():
    return "Hello World!"

def print_cond(a_bool, a_string):
    if a_bool:
        print("String is:")
        print(a_string())  # <-- note the ()


print_cond(True, lambda: f"some {difficult()} string")

打印:

String is:
some Hello World! string
© www.soinside.com 2019 - 2024. All rights reserved.