3

I know how to build nested progress bar using tqdm.

from tqdm import trange 
from time import sleep
for i in trange(10, desc='1st loop'):
    for j in trange(5, desc='2nd loop', leave=False):
        for k in trange(100, desc='3nd loop'): sleep(0.01)

I also know how to add postfixes and description to a bar

from tqdm import trange 
from random import random, randint 
from time import sleep 
with trange(100) as t: 
    for i in t: 
         t.set_description('GEN %i' % i) 
         t.set_postfix(loss=random(),  gen=randint(1,999), str='h', lst=[1, 2])   
         sleep(0.1)

Question

How can I add description and postfixes to nested progress bars in tqdm? I would like to add independent postfixes to each nested bar.

coder3101
  • 3,920
  • 3
  • 24
  • 28

1 Answers1

2

Nesting works fine:

from tqdm import trange
from time import sleep

n_epochs, n_steps = 5, 100
with trange(1, n_epochs + 1, desc="All epochs") as epochs:
    for epoch in epochs:
        with trange(1, n_steps + 1, desc="Epoch {}/{}".format(epoch, n_epochs)) as steps:
            for step in steps:
                epochs.set_postfix(foo=epoch * n_steps + step)
                steps.set_postfix(bar="hello {}".format(step), baz=1 / step)
                sleep(0.01)

Edit

The output looks like this when running (in this example, we're in the middle of the 3rd epoch):

Epoch 1/5: 100%|██████| 100/100 [00:01<00:00, 81.41it/s, bar=hello 100, baz=0.01]
Epoch 2/5: 100%|██████| 100/100 [00:01<00:00, 81.04it/s, bar=hello 100, baz=0.01]
All epochs:  40%|█████████▍              | 2/5 [00:03<00:04,  1.26s/it, foo=349]
Epoch 3/5:  48%|███▎  | 48/100 [00:00<00:00, 79.08it/s, bar=hello 49, baz=0.0204]

And it looks like this at the end:

Epoch 1/5: 100%|██████| 100/100 [00:01<00:00, 81.41it/s, bar=hello 100, baz=0.01]
Epoch 2/5: 100%|██████| 100/100 [00:01<00:00, 81.04it/s, bar=hello 100, baz=0.01]
Epoch 3/5: 100%|██████| 100/100 [00:01<00:00, 80.23it/s, bar=hello 100, baz=0.01]
Epoch 4/5: 100%|██████| 100/100 [00:01<00:00, 80.27it/s, bar=hello 100, baz=0.01]
Epoch 5/5: 100%|██████| 100/100 [00:01<00:00, 80.20it/s, bar=hello 100, baz=0.01]
All epochs: 100%|█████████████████████████| 5/5 [00:06<00:00,  1.24s/it, foo=600]
MiniQuark
  • 46,633
  • 36
  • 147
  • 183
  • I just tested this. It doesn't really work. The bar will span over new lines. – Eduardo Reis Feb 18 '21 at 19:12
  • @EduardoReis Thanks for your feedback. I'm not sure I see what you mean. Did you run this exact code? For me the output is great, and it spans just one line per epoch, plus one "All epochs" line. Is this what you mean by "Bar will span over new lines"? – MiniQuark Feb 20 '21 at 04:27
  • I updated my answer to show a sample output. – MiniQuark Feb 20 '21 at 04:39
  • [This answer](https://stackoverflow.com/a/66271987/2313889) might be also helpful. Check it out. – Eduardo Reis Feb 23 '21 at 19:19