Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing code that uses tqdm but seamlessly avoids it if tqdm is not installed

I want to write a python code that uses tqdm for showing a progress bar, but if tqdm is not available then my code should just run without using tqdm's progress bar and without raising an ImportError exception;

For example, when tqdm is available it should behave like this:

from tqdm import tqdm

def my_code(items):
    for item in tqdm(items, unit='item'):
        print(item)

..and when tqdm is not available it should behave like this:

def my_code(items):
    for item in items:
        print(item)

How can I do this?

I tried just wrapping the import line:

try:
    from tqdm import tqdm
except ImportError:
    pass

..but that did not prevent a NameError from appearing on the "for item in tqdm" line. I can wrap that line with a try catch as well.. but that just make it ugly :(

def my_code(items):
    try:
        tqdm_wrapper_if_exists = tqdm(items, unit='item')
    except NameError:
        tqdm_wrapper_if_exists = items
    for item in tqdm_wrapper_if_exists:
        print(item)

I want something that I can do it one place near the import error, and let the rest of the code run seamlessly without having to be adapted.

I also looked at Create a pass-through for an installed module to achieve an optional import but the question itself assumed creating a new tqdm.py file and adding it to the system path.. which makes the ugly I was trying to avoid even more vivid :) Moreover, the solutions discussed there does not allow to write the code seamlessly beyond the import statement, because you need to copy your tqdm.py file and add it to your path. I am looking for a much cleaner solution.

like image 200
jointfull Avatar asked Oct 24 '25 14:10

jointfull


1 Answers

Here's a simple solution:

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

this allows any code from that point to use tqdm when it is available, or to skip tqdm if it is not available.

like image 96
jointfull Avatar answered Oct 27 '25 05:10

jointfull