避免为特殊情况重写 FOR 循环
Avoid re-writing FOR loop for special cases
我所有的 python 脚本都接受一个名为 debug
的 bool 参数,如果为真,它会打印出一堆东西并使用 tqdm
循环进度条 for
]如下图
from tqdm import tqdm
for i in tqdm(range(1000)):
## rest of the calculation
但是,我想在调试为 false 时禁用 tqdm
进度条,除了在没有 tqdm
的情况下再次重写 for
循环之外,我不知道该怎么做(对于 debug=False 情况)。非常感谢任何有关如何更优雅地执行此操作的建议。
谢谢
有条件地定义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
循环仍然可以工作,无需修改或重复。
我所有的 python 脚本都接受一个名为 debug
的 bool 参数,如果为真,它会打印出一堆东西并使用 tqdm
循环进度条 for
]如下图
from tqdm import tqdm
for i in tqdm(range(1000)):
## rest of the calculation
但是,我想在调试为 false 时禁用 tqdm
进度条,除了在没有 tqdm
的情况下再次重写 for
循环之外,我不知道该怎么做(对于 debug=False 情况)。非常感谢任何有关如何更优雅地执行此操作的建议。
谢谢
有条件地定义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
循环仍然可以工作,无需修改或重复。