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

reversed(tqdm(some_list)) does not yield a reversed list #1484

Open
4 of 6 tasks
harmenwassenaar opened this issue Jul 23, 2023 · 0 comments
Open
4 of 6 tasks

reversed(tqdm(some_list)) does not yield a reversed list #1484

harmenwassenaar opened this issue Jul 23, 2023 · 0 comments

Comments

@harmenwassenaar
Copy link

harmenwassenaar commented Jul 23, 2023

  • I have marked all applicable categories:
    • exception-raising bug
    • visual output bug
  • I have visited the [source website], and in particular
    read the [known issues]
  • I have searched through the [issue tracker] for duplicates
  • I have mentioned version numbers, operating system and
    environment, where applicable:
    import tqdm, sys
    print(tqdm.__version__, sys.version, sys.platform)

Version info: 4.65.0 3.10.11 (main, Apr 5 2023, 00:00:00) [GCC 12.2.1 20221121 (Red Hat 12.2.1-4)] linux

When reversed is used on tqdm, it unexpectedly returns everything in the original, unreversed, order

>>> from tqdm import tqdm
>>> list(reversed(tqdm([1, 2, 3, 4])))
100%|██████████████████████████| 4/4 [00:00<00:00, 47798.34it/s]
[1, 2, 3, 4]
>>> 

This is because __reversed__ swaps in a reversed iterator, then stores the resulting generator it gets form calling self.__iter__(), and swaps the original iterator back before returning the generator. Crucially, because __iter__() is a generator, none of its code is executed before the first element is required. So by the time you use the generator, it's using the original iterator again.

There are a number of ways to solve this. The top answer on https://stackoverflow.com/q/5724009/1961666 suggests wrapping most of the code in __iter__ in a generator function, so that __iter__ is not itself a generator and so the first line would be run immediately when called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant