python - 是否可以延迟作为函数调用一部分的表达式的评估?
问题描述
在我的程序中,我多次出现这种模式:
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 字符串的评估延迟到它实际打印的点?
解决方案
您可以通过将 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
推荐阅读
- parameters - xgboost 模型中 n_estimators 的默认值是多少?
- tensorflow - 自定义损失函数以防止不对称混淆矩阵
- google-sheets-formula - 如何通过 IMPORTXML 从 Google 表格中的图书网站获取维度
- html - 如何用 CSS 设置形状?
- ios - 重复事件 Facebook 分析 iOS SDK
- telegram-bot - 如何将内联按钮的宽度更改为聊天宽度,而不是消息宽度
- django - 如何在 drf_spectacular (django) 中发送带有请求的自定义 JSON 标头?
- image - 为什么 Webpack 会复制图像和散列格式错误的图像
- javascript - 如何在 NodeJS spawn 中使用“eventcreate”?
- haskell - Haskell:无法将类型“Char”与“[Char]”匹配