Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for enumerate #1522

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions tests/tests_tqdm.py
Expand Up @@ -1980,3 +1980,8 @@ def test_contains(capsys):
assert not out
assert ' 0%' in err
assert '100%' not in err


def test_enumerate():
t = tqdm(enumerate(range(10)))
assert t.total == 10
5 changes: 4 additions & 1 deletion tqdm/std.py
Expand Up @@ -976,7 +976,10 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,

if total is None and iterable is not None:
try:
total = len(iterable)
if isinstance(iterable, enumerate):
total = len(list(iterable))
else:
total = len(iterable)
Comment on lines -979 to +982
Copy link

@niqodea niqodea Oct 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure this change will be approved. By calling list on the enumerate iterable you are potentially loading an entire dataset into memory, and also consuming the iterable.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could extract the wrapped iterable and work with that instead.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anyhow, the standard way to use tqdm together with enumerate is to wrap with tqdm first and enumerate second:

enumerate(tqdm(iterable))

except (TypeError, AttributeError):
total = None
if total == float("inf"):
Expand Down