首页 > 解决方案 > 是否可以延迟作为函数调用一部分的表达式的评估?

问题描述

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

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 字符串的评估延迟到它实际打印的点?

标签: pythonfunctionlazy-evaluation

解决方案


您可以通过将 f-string 放在 lambda 中来延迟对 f-string 的评估。

例如:

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

推荐阅读