tqdm color bar shows red if using break in Jupyter notebook

Question:

I use tqdm from tqdm.notebook to display a progress bar for iteration through lines of a file. I supply the total argument to give the number of iterations that will be performed (since I know it upfront) so the progress can be accurately displayed.

I use a break to stop at the maximum number of desired iterations (lines of the file to read).

Despite the fact that the number of iterations performed is equal to the value supplied to total in tqdm and the progress bar shows the maximum number of iterations have been performed (e.g. 11/11 in the example; see image), the bar is displayed in red (not green) indicating premature termination / an error.

I have already tried to assign the tqdm object to a variable and explicitly close the iterator in the condition before the break as per this related question.

How can I make the progress bar display correctly?

from tqdm.notebook import tqdm
LETTERS = list('ABCDEFGHIJKL')
for idx, letter in enumerate(tqdm(LETTERS, total=len(LETTERS)-1)):
    print(letter)
    if idx >= len(LETTERS) - 1:
        break

enter image description here


Version information (if helpful)

IPython : 8.1.1
ipykernel : 6.9.2
ipywidgets : 7.7.0
jupyter_client : 7.1.2
jupyter_core : 4.9.2
jupyter_server : not installed
jupyterlab : not installed
nbclient : 0.5.13
nbconvert : 6.4.4
nbformat : 5.2.0
notebook : 6.4.10
qtconsole : 5.2.2
traitlets : 5.1.1

Running with Python 3.8.10.

Asked By: Anil

||

Answers:

Because the break is in the last iteration, tqdm assumes that the loop stopped unintendedly, even if the loop is finished from the semantic side.

If you want to have a green progress bar in the end structure your code like this

from tqdm.notebook import tqdm

LETTERS = list('ABCDEFGHIJKL')
for idx, letter in enumerate(tqdm(LETTERS, total=len(LETTERS))):
    if idx == len(LETTERS):
        break
    print(letter)
Answered By: akra1
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.