Search code examples
pythonfunctionlazy-evaluation

Is it possible to delay the evaluation of an expression that is part of a function call?


In my program I have numerous occurrences of this pattern:

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

I thought about creating a function for this:

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

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

But the consequence of this is that the second parameter is always evaluated, even if some_bool == False. Is there a way to delay the evaluation of the f-string up to the point that it actually gets printed?


Solution

  • You can delay the evaluation of f-string by putting it inside lambda.

    For example:

    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")
    

    Prints:

    String is:
    some Hello World! string