Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I not require tqdm to be installed?

Tags:

python

tqdm

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).

like image 846
Merrick McCracken Avatar asked Oct 30 '25 05:10

Merrick McCracken


1 Answers

The way I usually do it is by adding the following shim:

try:
    from tqdm import tqdm
except ImportError:
    def tqdm(iterator, *args, **kwargs):
        return iterator

Now, you can just always use tqdm without having to worry about whether or not it exists, as the fallback will pass through the thing you're iterating over, ignoring all tqdm related options.

for item in tqdm(items):
    action(item)

Admittedly your usage (using with) isn't compatible with this approach - but I'll leave this here for people using it in a for loop like I usually use it.

like image 180
Shadow Avatar answered Nov 01 '25 18:11

Shadow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!