DustByte
DustByte

Reputation: 813

Display current item with tqdm progress bar

I would like to add the current item (string representation) to the tqdm progress bar.

Here is the code without any additional text (very short and concise):

from tqdm import tqdm
import time

animals = ["cat", "dog", "bird", "fish", "insect"]

for animal in tqdm(animals):
    time.sleep(1)
80%|████████  | 4/5 [00:04<00:01,  1.14s/it]

Here are two ways to display the item (here animal name) that is being processed:

progress = tqdm(animals)
for animal in progress:
    progress.set_postfix_str(animal)
    time.sleep(1)
40%|████      | 2/5 [00:02<00:04,  1.46s/it, bird]

and

with tqdm(total=len(animals)) as progress:
    for animal in animals:
        progress.set_postfix_str(animal)
        time.sleep(1)
        progress.update()
60%|██████    | 3/5 [00:03<00:02,  1.04s/it, fish]

Both methods add quite a bit of extra code and require a progress bar object to be specified. I have not found any simpler way of achieving this. Have I missed something that tqdm has to offer?

In particular I have been looking for a way to tell tqdm to output the string (use say __str__()) of the item that its iterator is returning. E.g.,

for animal in tqdm(animals, postfix="{item}")  # Note: does not work!
    time.sleep(1)

Upvotes: 19

Views: 8302

Answers (1)

Anatoly Alekseev
Anatoly Alekseev

Reputation: 2410

Looks like the only way to save one extra line is by using a walrus operator added in Python 3.8:

for animal in (pbar:= tqdm(animals)) :
    pbar.set_postfix_str(animal)
    time.sleep(1)

100% 5/5 [00:05<00:00, 1.01s/it, insect]

Upvotes: 15

Related Questions