Changing description after a for cycle in tqdm

Viewed 4946

Is it possible to set the description of a tqdm progress bar out of its for loop?

A simple example:

with tqdm(range(100), desc='processing') as pbar:
    x = 0
    for i in pbar:
        x += i
    y = x ** 2
    # 3. set description of pbar 'y = {}'.format(y)'

What should I put in place of 3.?

EDIT: More precisely, I want to compute y after having executed the for loop entirely, then I want to log the y value in the progress bar description (replacing the 'processing' description).

1 Answers

You may have a slight misunderstanding with how tqdm works. There is a simple inbuit command set_description(), to set the description for the tqdm progress bar as its looping. In your example code if you try setting the description where you have your comment nothing would happen as you have already finished looping over pbar. (though that may just be due to incorrect indentation)

Here is a simple example that shows how the description changes -

from tqdm import tqdm
import time

pbar = tqdm(range(100), desc='description')

x = 0
for i in pbar:
    x += i
    y = x**2
    pbar.set_description("y = %d" % y)
    time.sleep(0.5)

This will allow you to see how the description changes over each loop iteration.

Related