9

The following simple code uses tqdm to display a progress bar while iterating over a loop:

import tqdm
for f in tqdm.tqdm(range(100000000)):
  if f > 100000000/4:
    break

It fails when the break is executed:

$ python test.py 
 24%|████▎ | 24425076/100000000 [00:03<00:11, 6550673.18it/s]
Exception KeyError: KeyError(<weakref at 0x7fb8799f1158; to 'tqdm' at 0x7fb8799de190>,) in  ignored

I am using Python v2.7.6, and tqdm v4.32.1:

$ python --version
Python 2.7.6
$ python -m tqdm --version
4.23.1

I looked for similar errors on the Internet with no positive outcome.

lackadaisical
  • 1,278
  • 14
  • 19
  • I don't use the library but it looks like you're deliberately breaking out at 25%? How should a progress bar respond to that? – roganjosh Aug 25 '18 at 12:55
  • I was trying to use tqdm in a loop that can stop when a given condition is true. – lackadaisical Aug 25 '18 at 13:05
  • @roganjosh when an error occurs you might want to update or abandon the progress bar without other errors occurring that might confuse the following logic or messages provided to the user. – Jason Harrison Feb 05 '21 at 22:09

1 Answers1

15

It turns out the tqdm iterator has to be closed manually when it is interrupted:

import tqdm
iterator = tqdm.tqdm(range(100000000))
for f in iterator:
  if f > 100000000/4:
    iterator.close()
    break

This executes without problems.

lackadaisical
  • 1,278
  • 14
  • 19