Make the largest loops lazier and async to avoid blocking #3767

Merged
Drapersniper merged 39 commits from no-block-loops into V3/develop 2020-04-20 19:56:29 +02:00
Drapersniper commented 2020-04-18 13:47:05 +02:00 (Migrated from github.com)

Type

  • Bugfix
  • Enhancement
  • New feature

Description of the changes

This one depends on #3766

### Type - [ ] Bugfix - [x] Enhancement - [ ] New feature ### Description of the changes This one depends on #3766
palmtree5 (Migrated from github.com) reviewed 2020-04-18 13:47:05 +02:00
tekulvw (Migrated from github.com) reviewed 2020-04-18 13:47:05 +02:00
Twentysix26 (Migrated from github.com) reviewed 2020-04-18 13:47:05 +02:00
Tobotimus (Migrated from github.com) reviewed 2020-04-18 13:47:05 +02:00
aikaterna (Migrated from github.com) reviewed 2020-04-18 13:47:05 +02:00
Jackenmen (Migrated from github.com) requested changes 2020-04-19 17:52:32 +02:00
@ -55,7 +56,7 @@ class Announcer:
async def announcer(self):
Jackenmen (Migrated from github.com) commented 2020-04-19 14:52:43 +02:00

It would be better to use asyncio.gather here but I guess it's kind of out of scope for this PR.

It would be better to use `asyncio.gather` here but I guess it's kind of out of scope for this PR.
@ -8,3 +8,4 @@
import discord
from redbot.core import commands, i18n, checks, modlog
from redbot.core.utils import AsyncIter
from redbot.core.utils.chat_formatting import pagify, humanize_number, bold
Jackenmen (Migrated from github.com) commented 2020-04-19 14:56:04 +02:00

It's a nitpick but I think it would be clearer to do from redbot.core.utils import AsyncGen

It's a nitpick but I think it would be clearer to do `from redbot.core.utils import AsyncGen`
@ -37,25 +38,25 @@ class GlobalUniqueObjectFinder(commands.Converter):
if user is not None:
Jackenmen (Migrated from github.com) commented 2020-04-19 15:03:06 +02:00

This and the all_roles list that was added above can be simplified to:

            *(
                filter(lambda r: not r.is_default(), guild.roles)
                async for guild in AsyncGen(bot.guilds, steps=100)
            ),

That also means that all_roles from above can be removed.

This and the `all_roles` list that was added above can be simplified to: ```suggestion *( filter(lambda r: not r.is_default(), guild.roles) async for guild in AsyncGen(bot.guilds, steps=100) ), ``` That also means that `all_roles` from above can be removed.
Jackenmen (Migrated from github.com) commented 2020-04-19 15:07:47 +02:00

This whole thing should be done differently - we should stop when we figure out there's more than one match.

This whole thing should be done differently - we should stop when we figure out there's more than one match.
Jackenmen (Migrated from github.com) commented 2020-04-19 17:51:04 +02:00

I didn't test this but I doubt this works at all - any() can be used with regular iterables, not with async iterables.

I didn't test this but I doubt this works at all - `any()` can be used with regular iterables, not with async iterables.
Jackenmen (Migrated from github.com) commented 2020-04-19 15:09:17 +02:00

Same as above, we should stop iterating when figure out there's more than one match.

Same as above, we should stop iterating when figure out there's more than one match.
@ -18,9 +19,10 @@ from typing import (
Union,
Set,
TYPE_CHECKING,
Jackenmen (Migrated from github.com) commented 2020-04-19 16:13:27 +02:00

It's not a part of the PR, but could you add bounded_gather_iter to __all__?

__all__ = ("bounded_gather", "bounded_gather_iter", "deduplicate_iterables", "AsyncGen")
It's not a part of the PR, but could you add `bounded_gather_iter` to `__all__`? ```suggestion __all__ = ("bounded_gather", "bounded_gather_iter", "deduplicate_iterables", "AsyncGen") ```
Jackenmen (Migrated from github.com) commented 2020-04-18 21:54:07 +02:00

Incorrect type hint, it should be:

    async def __anext__(self) -> _T:
Incorrect type hint, it should be: ```suggestion async def __anext__(self) -> _T: ```
Jackenmen (Migrated from github.com) commented 2020-04-18 21:54:34 +02:00

item will be clearer than i, especially considering we already use i for index.

            item = next(self.content)
`item` will be clearer than `i`, especially considering we already use `i` for index. ```suggestion item = next(self.content) ```
Jackenmen (Migrated from github.com) commented 2020-04-18 21:54:41 +02:00

item will be clearer than i, especially considering we already use i for index.

        return item
`item` will be clearer than `i`, especially considering we already use `i` for index. ```suggestion return item ```
Jackenmen (Migrated from github.com) commented 2020-04-18 21:59:39 +02:00

Add type hint (remember to import Generator from typing)

    def __await__(self) -> Generator[Any, None, List[_T]]:
Add type hint (remember to import `Generator` from `typing`) ```suggestion def __await__(self) -> Generator[Any, None, List[_T]]: ```
Jackenmen (Migrated from github.com) commented 2020-04-18 22:00:08 +02:00

Add type hint (you need to add from __future__ import annotations at the top of the file):

    def __aiter__(self) -> AsyncGen[_T]:
Add type hint (you need to add `from __future__ import annotations` at the top of the file): ```suggestion def __aiter__(self) -> AsyncGen[_T]: ```
Jackenmen (Migrated from github.com) commented 2020-04-18 22:01:08 +02:00

Considering we're passing iterable (iterator is an iterable), I think it would be clearer to call it iterable instead of contents

I also have two suggestions for typings here:
a) we can simplify Union[Iterator[_T], Iterable[_T]] to just Iterable[_T] as all iterators are iterable
b) since float is not an int, we need to specify union of both here if we want to accept both (and since it's only used for asyncio.sleep(), I think we do want it)

        self, iterable: Iterable[_T], delay: Union[float, int] = 0, steps: int = 1
Considering we're passing iterable (iterator is an iterable), I think it would be clearer to call it `iterable` instead of `contents` I also have two suggestions for typings here: a) we can simplify `Union[Iterator[_T], Iterable[_T]]` to just `Iterable[_T]` as all iterators are iterable b) since `float` is not an `int`, we need to specify union of both here if we want to accept both (and since it's only used for `asyncio.sleep()`, I think we do want it) ```suggestion self, iterable: Iterable[_T], delay: Union[float, int] = 0, steps: int = 1 ```
Jackenmen (Migrated from github.com) commented 2020-04-18 22:01:22 +02:00

I think it would be clearer if this attribute were called iterator (or it if you prefer short version)

I think it would be clearer if this attribute were called `iterator` (or `it` if you prefer short version)
Jackenmen (Migrated from github.com) commented 2020-04-18 22:02:02 +02:00

This needs a better name - this doesn't remove duplicates, it gives you iterator without duplicated entries, maybe it should be called without_duplicates()?

This needs a better name - this doesn't remove duplicates, it gives you iterator without duplicated entries, maybe it should be called `without_duplicates()`?
Jackenmen (Migrated from github.com) commented 2020-04-18 22:02:20 +02:00

Add type hint:

    async def remove_dupes(self) -> AsyncIterator[_T]:
Add type hint: ```suggestion async def remove_dupes(self) -> AsyncIterator[_T]: ```
Jackenmen (Migrated from github.com) commented 2020-04-18 22:03:02 +02:00

I think all these attributes should be private.

I think all these attributes should be private.
Jackenmen (Migrated from github.com) commented 2020-04-18 22:07:55 +02:00
  • I think using async_enumerate would be better here just so that all the logic is in one place.
  • start is missing type hint
    def enumerate(self, start: int = 0) -> AsyncIterator[Tuple[int, _T]]:
        return async_enumerate(self, start)
- I think using `async_enumerate` would be better here just so that all the logic is in one place. - `start` is missing type hint ```suggestion def enumerate(self, start: int = 0) -> AsyncIterator[Tuple[int, _T]]: return async_enumerate(self, start) ```
Jackenmen (Migrated from github.com) commented 2020-04-18 22:11:04 +02:00

You need to return the result of the coro.__await__() not coro itself from __await__ function:

        return self.flatten().__await__()
You need to return the result of the `coro.__await__()` not `coro` itself from `__await__` function: ```suggestion return self.flatten().__await__() ```
Jackenmen (Migrated from github.com) commented 2020-04-19 14:53:41 +02:00

Better docstring needed (list parameters and their expected types as with any other function in this file)

We should also be a little more descriptive about what this does. Something more like (still needs to be better worded):

Asynchronous iterator yielding items from ``iterable`` that sleeps for ``delay`` seconds every ``steps`` items.

Last but not least, you need to add automethod directive for this class to docs/framework_utils.rst

Better docstring needed (list parameters and their expected types as with any other function in this file) We should also be a little more descriptive about what this does. Something more like (still needs to be better worded): ``` Asynchronous iterator yielding items from ``iterable`` that sleeps for ``delay`` seconds every ``steps`` items. ``` Last but not least, you need to add `automethod` directive for this class to `docs/framework_utils.rst`
Jackenmen (Migrated from github.com) commented 2020-04-19 15:31:28 +02:00

This class is not just AsyncIterable but also AsyncIterator so that generic suits it better. It can also be awaited so I think you should add Awaitable generic as well.

class AsyncGen(AsyncIterator[_T], Awaitable[List[_T]]):  # pylint: disable=duplicate-bases
This class is not just `AsyncIterable` but also `AsyncIterator` so that generic suits it better. It can also be awaited so I think you should add `Awaitable` generic as well. ```suggestion class AsyncGen(AsyncIterator[_T], Awaitable[List[_T]]): # pylint: disable=duplicate-bases ```
Jackenmen (Migrated from github.com) commented 2020-04-19 15:34:48 +02:00

Since we don't care about order in _temp here, can you use set for better performance?

Since we don't care about order in `_temp` here, can you use `set` for better performance?
Jackenmen (Migrated from github.com) commented 2020-04-19 15:45:35 +02:00

This class name (AsyncGen) might be confusing - despite of what the name says, this isn't async generator, it's async iterator (and these two terms are different).

This class name (`AsyncGen`) might be confusing - despite of what the name says, this isn't async generator, it's async iterator (and these two terms are different).
Jackenmen (Migrated from github.com) commented 2020-04-19 17:24:53 +02:00
  • Arguments are passed in wrong order to async_filter()
  • function's type hint is incorrect
  • I think *args, **kwargs are unnecessary here, if someone wants to, they can pass partial themselves.
  • This whole function can be simplified to regular function returning result of async_filter() function:
    def filter(self, function: Callable[[_T], Union[bool, Awaitable[bool]]]) -> AsyncFilter[_T]:
        return async_filter(function, self)
- Arguments are passed in wrong order to `async_filter()` - `function`'s type hint is incorrect - I think `*args, **kwargs` are unnecessary here, if someone wants to, they can pass partial themselves. - This whole function can be simplified to regular function returning result of `async_filter()` function: ```suggestion def filter(self, function: Callable[[_T], Union[bool, Awaitable[bool]]]) -> AsyncFilter[_T]: return async_filter(function, self) ```
Drapersniper (Migrated from github.com) reviewed 2020-04-19 18:21:13 +02:00
@ -37,25 +38,25 @@ class GlobalUniqueObjectFinder(commands.Converter):
if user is not None:
Drapersniper (Migrated from github.com) commented 2020-04-19 18:21:13 +02:00

This is out of the scope of this PR no? I mean im happy to address it but .. just want to be sure

This is out of the scope of this PR no? I mean im happy to address it but .. just want to be sure
Jackenmen (Migrated from github.com) requested changes 2020-04-19 20:58:54 +02:00
@ -10,6 +10,17 @@ General Utility
.. automodule:: redbot.core.utils
:members: deduplicate_iterables, bounded_gather, bounded_gather_iter
.. autoclass:: AsyncIter
Jackenmen (Migrated from github.com) commented 2020-04-19 20:29:05 +02:00

For the methods to show as async for ... in enumerate(start=) we need to manually indicate it for these two methods:
image


.. autoclass:: AsyncIter
    :members:
    :exclude-members: enumerate, filter

    .. automethod:: enumerate
        :async-for:

    .. automethod:: filter
        :async-for:

For the methods to show as `async for ... in enumerate(start=)` we need to manually indicate it for these two methods: ![image](https://user-images.githubusercontent.com/6032823/79696560-a17bf600-827d-11ea-8bf3-df493adc13b7.png) ```suggestion .. autoclass:: AsyncIter :members: :exclude-members: enumerate, filter .. automethod:: enumerate :async-for: .. automethod:: filter :async-for: ```
@ -255,3 +257,131 @@ def bounded_gather(
tasks = (_sem_wrapper(semaphore, task) for task in coros_or_futures)
Jackenmen (Migrated from github.com) commented 2020-04-19 20:40:46 +02:00

bad indentation here

            >>> from redbot.core.utils import AsyncIter
            >>> def predicate(value):
            >>>     return value <= 5
            >>> iterator = AsyncIter([1, 10, 5, 100])
            >>> await iterator.filter(predicate)
            [1, 5]
bad indentation here ```suggestion >>> from redbot.core.utils import AsyncIter >>> def predicate(value): >>> return value <= 5 >>> iterator = AsyncIter([1, 10, 5, 100]) >>> await iterator.filter(predicate) [1, 5] ```
Jackenmen (Migrated from github.com) commented 2020-04-19 20:41:33 +02:00

Let's use 4 space indent here

            >>>     return value <= 5
Let's use 4 space indent here ```suggestion >>> return value <= 5 ```
Jackenmen (Migrated from github.com) commented 2020-04-19 20:44:40 +02:00

Wouldn't it make more sense to call this self._iterator?

Wouldn't it make more sense to call this `self._iterator`?
@ -258,0 +339,4 @@
def enumerate(self, start: int = 0) -> AsyncIterator[Tuple[int, _T]]:
"""Async iterable version of `enumerate`.
Jackenmen (Migrated from github.com) commented 2020-04-19 20:42:44 +02:00

This looks incomplete, maybe you wanted to add a print() here?

            >>> async for i in iterator.filter(predicate):
            >>>     print(i)
This looks incomplete, maybe you wanted to add a `print()` here? ```suggestion >>> async for i in iterator.filter(predicate): >>> print(i) ```
@ -258,0 +371,4 @@
--------
>>> from redbot.core.utils import AsyncIter
>>> iterator = AsyncIter([1,2,3,3,4,4,5])
>>> async for i in iterator.without_duplicates():
Jackenmen (Migrated from github.com) commented 2020-04-19 20:43:37 +02:00

This looks incomplete, maybe you wanted to add a print() here?

            >>> async for i in iterator.enumerate(start=10):
            >>>     print(i)
This looks incomplete, maybe you wanted to add a `print()` here? ```suggestion >>> async for i in iterator.enumerate(start=10): >>> print(i) ```
Jackenmen (Migrated from github.com) commented 2020-04-19 20:44:07 +02:00

This looks incomplete, maybe you wanted to add a print() here?

            >>> async for i in iterator.without_duplicates():
            >>>     print(i)
This looks incomplete, maybe you wanted to add a `print()` here? ```suggestion >>> async for i in iterator.without_duplicates(): >>> print(i) ```
Jackenmen (Migrated from github.com) requested changes 2020-04-19 21:02:29 +02:00
@ -255,3 +257,131 @@ def bounded_gather(
tasks = (_sem_wrapper(semaphore, task) for task in coros_or_futures)
Jackenmen (Migrated from github.com) commented 2020-04-19 21:01:45 +02:00
        self._iterator = iter(iterable)
```suggestion self._iterator = iter(iterable) ```
Jackenmen (Migrated from github.com) commented 2020-04-19 21:01:55 +02:00
            item = next(self._iterator)
```suggestion item = next(self._iterator) ```
Jackenmen (Migrated from github.com) reviewed 2020-04-19 22:24:41 +02:00
@ -37,25 +38,25 @@ class GlobalUniqueObjectFinder(commands.Converter):
if user is not None:
Jackenmen (Migrated from github.com) commented 2020-04-19 22:24:40 +02:00

This isn't actually a valid code - * can't be used with async iterators

This isn't actually a valid code - `*` can't be used with async iterators
Jackenmen (Migrated from github.com) requested changes 2020-04-20 11:02:10 +02:00
@ -255,3 +257,131 @@ def bounded_gather(
tasks = (_sem_wrapper(semaphore, task) for task in coros_or_futures)
Jackenmen (Migrated from github.com) commented 2020-04-20 03:10:01 +02:00
            ...     print(i)
```suggestion ... print(i) ```
Jackenmen (Migrated from github.com) commented 2020-04-20 03:10:10 +02:00
            ...     print(i)
```suggestion ... print(i) ```
Jackenmen (Migrated from github.com) commented 2020-04-20 03:10:17 +02:00
            ...     return value <= 5
```suggestion ... return value <= 5 ```
Jackenmen (Migrated from github.com) commented 2020-04-20 03:10:36 +02:00
            ...     return value <= 5
```suggestion ... return value <= 5 ```
Jackenmen (Migrated from github.com) commented 2020-04-20 03:10:55 +02:00
            ...     print(i)
```suggestion ... print(i) ```
Jackenmen (Migrated from github.com) approved these changes 2020-04-20 19:55:36 +02:00
Sign in to join this conversation.
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Mrcoolgamer11/Red-DiscordBot!3767
No description provided.