Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add message to the tqdm progressbar?

Tags:

python

tqdm

People also ask

Is tqdm only for loops?

I think tqdm is meant for long loops, not short loops that takes a lot of time. That is because tqdm estimates the ETA based on the average time it took a cycle to complete, so it wont be that useful.

Does tqdm affect performance?

In addition, a huge benefit of using tqdm instead of a different method for showing a progress bar is that tqdm has little overhead, around 60 nanoseconds per iteration — meaning it should not affect performance much, compared to something like ProgressBar, which has an overhead of 800 nanoseconds per iteration.

Can I use tqdm in while loop?

tqdm does not require any dependencies and works across multiple python environments. Integrating tqdm can be done effortlessly in loops, on iterable, with Pandas or even with machine learning libraries— just wrap any iterable with tqdm(iterable) , and you're done!


The example shown in Usage of tqdm works well for me.

pbar = tqdm(["a", "b", "c", "d"])
for char in pbar:
    pbar.set_description("Processing %s" % char)

You can change the description to show a small message before the progress bar, like this:

from tqdm import trange
from time import sleep
t = trange(100, desc='Bar desc', leave=True)
for i in t:
    t.set_description("Bar desc (file %i)" % i)
    t.refresh() # to show immediately the update
    sleep(0.01)

/EDIT: in the latest releases of tqdm, you can use t.set_description("text", refresh=True) (which is the default) and remove t.refresh() (thanks to Daniel for the tip).


Other answers focus on dynamic description, but for a static description you can add a desc argument into the tqdm function.

from tqdm import tqdm

x = [5]*1000
for _ in tqdm(x, desc="Example"):
    pass
 
Example: 100%|██████████████████████████████████| 1000/1000 [00:00<00:00, 1838800.53it/s]

You can use set_postfix to add values directly to the bar.

Example:

from tqdm import tqdm
pbar = tqdm(["a", "b", "c", "d"])
num_vowels = 0
for ichar in pbar:
    if ichar in ['a','e','i','o','u']:
        num_vowels += 1
    pbar.set_postfix({'num_vowels': num_vowels})

The postfix dictionary is integrated into the progress bar:

100%|███████████| 4/4 [00:11<00:00,  2.93s/it, num_vowels=1]

Instead of a dictionary, you can use set_postfix_str to just add a string to the end of the progress bar.


I personally find it much cleaner to use the with statement:

from tqdm import tqdm

with tqdm(['a','b','c']) as t:
  for c in t:
    t.set_description(f'{c}')