2

I'm using tqdm as a nice progressbar, but after iterating over the progressbar I want to update the description.

The following is a simple example:

with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)

  pbar.set_description('We finished')

I get the output:

100%|███████████████████████████████████████| 10/10 [00:00<00:00, 239674.51it/s]

but expected:

We finished: 100%|███████████████████████████| 10/10 [00:00<00:00, 239674.51it/s]

I've tried pbar.update(), pbar.refresh() and refresh=True as a parameter for set_description, neither worked.

Of course, one can always print or use tqdm.write(), but would be neater to have besides the progress bar.

Theis Jendal
  • 71
  • 1
  • 6

1 Answers1

0

Have you tried this code below? You can check if the current element is the last item in some list by using the if condition if element == somelist[-1]. If the element is the last item in somelist, then you know it will be finished after this so you can update the pbar description

with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)
    if element == somelist[-1]:
        # Update when element is the last item in some list
        pbar.set_description("We finished")

Edit: Another way is to use an increasing i variable to check if it is at the end of the iteration or now

i = 0
with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)
    i += 1
    if i == len(somelist):
        # Update when element is the last item in some list
        pbar.set_description("We finished")
tax evader
  • 2,082
  • 1
  • 7
  • 9
  • `somelist` in my case is a pytorch `DataLoader` which isn't subscriptable. I could enumerate over the loader, and check when `len(somelist) == i`, though it is not as nice looking in my opinion and would have a lot of code indented in the if statement. – Theis Jendal Mar 31 '21 at 13:29
  • @TheisJendal If you can set a variable `I = 0` and increase it by 1 every iteration. We can know if it is the end of the iteration by checking if `len(somelist) == I` – tax evader Mar 31 '21 at 15:41