Search code examples
pythonwith-statement

How can I insert a 'with' statement under a condition?


I have a piece of code structured this way:

try:
    from tqdm import tqdm
    use_tqdm = True
except ImportError:
    use_tqdm = False


if use_tqdm:
    with tqdm(total=5) as pbar:
        # --- many nested for loops ---
        pbar.update(1)
else:
    # --- identical nested for loops, without pbar.update(1) ---

How can I avoid repeating said long block of code?

I cannot put the condition only on the single pbar line inside because what tqdm does is create a progress bar, so it needs to be instantiated only once.

I think I'm looking for a way to tell Python "hey, consider the with statement only if use_tqdm = True, otherwise pretend it never existed", but any other suggestions are very welcome.

Thanks!

(tqdm package: https://github.com/tqdm/tqdm )


Solution

  • try:
        from tqdm import tqdm
    except ImportError:
        class tqdm:
            def __int__(self, *args, **kwargs):
                pass
    
            def __enter__(self):
                class Dummy:
                    def update(self, *args, **kwargs):
                        pass
    
                return Dummy()
    
            def __exit__(self, *args):
                pass
    
    with tqdm(total = 5) as pbar:
       --- many nested for loops ---
                pbar.update(1)
    

    If the import fails, you just get a dummy context and an object whose update method is a no-op. No separate code is needed.