【问题标题】:Is it possible to delay the evaluation of an expression that is part of a function call?是否可以延迟作为函数调用一部分的表达式的评估?
【发布时间】:2026-01-22 01:25:01
【问题描述】:

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

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】:

    您可以通过将 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
    

    【讨论】:

      最近更新 更多