【问题标题】:Avoid re-writing FOR loop for special cases避免为特殊情况重写 FOR 循环
【发布时间】:2020-05-26 03:27:59
【问题描述】:

我所有的 python 脚本都接受一个名为 debug 的 bool 参数,如果为真,则打印出大量内容并使用 tqdm 执行 for 循环进度条,如下所示

from tqdm import tqdm
for i in tqdm(range(1000)):
     ## rest of the calculation

但是,当 debug 为 false 时,我想禁用 tqdm 进度条,除了在没有 tqdm 的情况下再次重写 for 循环(对于 debug=False 的情况)之外,我不确定如何执行此操作。非常感谢任何有关如何更优雅地执行此操作的建议。

谢谢

【问题讨论】:

    标签: python for-loop tqdm


    【解决方案1】:

    有条件地定义tqdm

    if debug:
        from tqdm import tqdm
    else:
        def tqdm(x):  # Noop version when not in debug mode
            return x
    
        # Alternative version that's slightly less clear,
        # but probably slightly more performant, due to using built-in:
        tqdm = iter  # Explicitly make it convert the input to an iterator, but do nothing else
    

    这使得tqdm 在不处于调试模式时成为空操作,因此您的原始for 循环仍然可以正常工作而无需修改或复制。

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多