serhii.net

In the middle of the desert you can say anything you want

04 May 2022

Use tqdm only if the list is large

Wrote this small wrapper script that (if a global USE_TQDM parameter is set) uses pretty tqdm lists on lists that have enough elements where it matters. I think I’ll be reusing it.

So when enabled, it will tqdm a list of 150 elements but won’t tqdm a list of 99 elements.

To use:

for el in _tqdm(whatever_list_thing):
	do_stuff_to(el)

Function:

def _tqdm(list_like: Sequence, iflarge: bool = False, lsize: int = 100):
    """Use tqdm if it's on, optionally based on length of list.
    Args:
        list_like: thing to iterate.
        iflarge (bool): If on, will use tqdm only for large lists
        lsize (int): anything more than this is 'large'
    """
    if USE_TQDM:
        if not iflarge:
            return tqdm(list_like)
        else:
            # Count size only if it doesn't mean iterating an iterator
            if isinstance(list_like, Sequence) and len(list_like) > lsize:
                return tqdm(list_like)
    return list_like
Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus