Search code examples
pythonprogressfallbacktqdm

Simple fallback progressbar when tqdm is not available


I have a python package that uses the tqdm progressbar. However, I don't want this to be a hard dependency for the users of my package. Is there some simple drop-in solution that can easily act as fallback if tqdm is not installed?

I am using the total and leave property of tqdm.tqdm(), as well as the update and close methods of the tqdm.tqdm instance.


Solution

  • Sure.

    def noobar(itrble, desc):
      """Simple progress bar. To be used if tqdm not installed."""
      L  = len(itrble)
      print('{}: {: >2d}'.format(desc,0), end='')
      for k,i in enumerate(itrble):
        yield i
        p = (k+1)/L
        e = '' if k<(L-1) else '\n'
        print('\b\b\b\b {: >2d}%'.format(int(100*p)), end=e)
        sys.stdout.flush()
    

    Try it with

    from time import sleep
    for i in noobar(range(5),"my work"):
      sleep(1)