Reputation: 9003
I want to construct trange
but to use it later. For example:
from tqdm import trange
if progress:
r = trange(10)
else:
r = range(10)
for _ in r:
# do something
However, at the construction time, trange
will print an empty progress line (with 0%), and later it will print a new one (as expected).
How to avoid this?
Obviously, there are tricks to work around this, for example:
for _ in trange(10) if progress else range(10):
# do something
or what @BatWannaBe suggests below.
However, I would prefer something cleaner. Why does trange
print anything at construction time, in the first place?
Upvotes: 1
Views: 11378
Reputation: 1254
Is this cleaner?
from tqdm import trange
progress = False # We should see no tqdm now
if progress:
r = lambda n: trange(n)
else:
r = lambda n: range(n)
for _ in r(10):
# do something
...
Upvotes: 0
Reputation: 4510
It seems like the progress bar shows up whenever a tqdm.tqdm
instance is constructed, which trange
does: trange(n)
is shorthand for tqdm.tqdm(range(n))
. I'm not sure if there's any way around that.
However, you can delay the construction by keeping a temporary range(n)
object.
from tqdm import tqdm
r = range(10)
if progress:
for _ in tqdm(r):
# do something
else:
for _ in r:
# do something
If progress
is True
/False
, you could reduce the duplicated code with this trick treating False
as 0 and True
as 1:
maybetqdm = [lambda x:x, tqdm] # lambda x:x is function that does nothing
for _ in maybetqdm[progress](r):
# do something
Upvotes: 1