Search code examples
pythonfor-looptqdm

Avoid re-writing FOR loop for special cases


All my python scripts take in a bool argument called debug, which if True, prints out a load of stuff and does for loop progress bar using tqdm as shown below

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

However, I would like to disable the tqdm progress bar when debug is false and I am not sure how to do this other than rewriting the for loop again without tqdm (for debug=False case). Any suggestions on how to do this more elegantly are much appreciated.

Thanks


Solution

  • Define tqdm conditionally:

    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
    

    That makes tqdm a no-op when not in debug mode, so your original for loop still works without modification or duplication.