Search code examples
pythontqdm

How can I not require tqdm to be installed?


I'd like to use tqdm in my script but not require others to use it if they haven't installed it.

I've found this:

try:
    import tqdm
except ImportError:
    tqdm = None

But I'm not sure how to use tqdm==None with this:

with tqdm.tqdm(total=totalSize) as pbar:

Where totalSize is the file size (or sum of file sizes when looping over multiple files).


Solution

  • With help from tqdm's documentation and my try/except logic, I have this working:

    try:
        import tqdm
    except ImportError:
        tqdm = None
    
    if (tqdm == None):
        pbar = None
    else:
        pbar = tqdm.tqdm(total=totalSize)
    
    #... inside the loop processing my file[s]...
    if (pbar):
        pbar.update(len(line))