Separate inner logic of function from displaying user information using tqdm

38 views Asked by At

I wonder if it is possible to separate the logic of a function from the user information displayed with tqdm? Currently, my function takes in a verbose argument and includes an if-else statement so that the user information is displayed or not depending on the user's input. But I think it would be cleaner if the function itself wouldn't have anything to do with user information and that verbosity could somehow be defined outside of its scope (that would allow me to get rid of the if-else statement and the verbose argument). Currently I do something like this:

from tqdm import trange
from time import sleep

# user defined
verbose = True

def my_function(verbose):
    
    if verbose == True:
        for i in trange(100):
            sleep(0.01)
            
    elif verbose == False:
        for i in range(100):
            sleep(0.01)
            
            
my_function(verbose)

EDIT: The code above is just an example of a tqdm progress bar. I don't look for an exact solution that works with trange but I might also end up using any of the other implementations. I should specify that I only know that this function does something using an iterable / for-loop + I want to use tqdm to print the progress to the console + I want this function to be either verbose or not without having to use an if-else statement inside that function.

Instead, is it possible to do something like this?

verbose = True

if verbose == True:
    with tqdm():
        my_function()
elif verbose == False:
    my_function()

1

There are 1 answers

1
Andrej Kesely On

One possible solution is use custom context manager where you override trange() to normal range() when the verbose == False:

from contextlib import contextmanager
from time import sleep

from tqdm import trange


@contextmanager
def verbose_range(verbose):
    global trange
    try:
        __trange = trange
        if not verbose:
            trange = range
        yield
    finally:
        trange = __trange


def my_function():
    for i in trange(100):
        sleep(0.01)


with verbose_range(True):
    my_function()

Prints:

100%|█████████████████████████████████████████████████| 100/100 [00:01<00:00, 99.30it/s]