Repository: hikari-py/hikari
Pull request #742 (2021-08-23 13:58:01)

Consistency fixes for `__all__` usages
### Checklist
<!-- Make sure to tick all the following boxes by putting an `x` in between (like this `[x]`) -->
- [x] I have run `nox` and all the pipelines have passed.
- [x] I have made unittests according to the code I have added/modified/deleted.


davfsa: Also, random thing I found out while doing this (just for fun), if we turn all `__all__` into tuples, we save about ~1MB of memory if the package is imported :)

Patch:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1ef35240..6e42da5b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -155,18 +155,28 @@ jobs:
           retention-days: 2
           if-no-files-found: error
 
-  # This job is only used to mark the CI as being done
-  #
   # Allows us to add this as a required check in Github branch rules, as all the
   # other jobs are subject to change
   ci-done:
     needs: [upload-coverage, linting, twemoji, pages]
+    if: always()
 
     runs-on: ubuntu-20.04
 
     steps:
-      - name: Completed
-        run: echo "CI Completed"
+      - name: Mark status based on past job status
+        env:
+          # All new need jobs need to be added here with the prefix "RESULT_"
+          RESULT_UPLOAD_COVERAGE: ${{ needs.upload-coverage.result }}
+          RESULT_LINTING: ${{ needs.linting.result }}
+          RESULT_TWEMOJI: ${{ needs.twemoji.result }}
+          RESULT_PAGES: ${{ needs.pages.result }}
+        run: |
+          if [ "$(env | grep 'RESULT_')" = "$(env | grep "RESULT_" | grep '=success')" ]; then
+            exit 0
+          else
+            exit 1
+          fi
 
   deploy:
     if: github.event_name == 'release'
diff --git a/hikari/api/interaction_server.py b/hikari/api/interaction_server.py
index a0714145..bc04be1c 100644
--- a/hikari/api/interaction_server.py
+++ b/hikari/api/interaction_server.py
@@ -23,7 +23,7 @@
 """Provides an interface for Interaction REST server API implementations to follow."""
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = ["ListenerT", "Response", "InteractionServer"]
+__all__: typing.List[str] = ["ListenerT", "Response", "InteractionServer"]
 
 import abc
 import typing
diff --git a/hikari/errors.py b/hikari/errors.py
index feee3ddf..088734d1 100644
--- a/hikari/errors.py
+++ b/hikari/errors.py
@@ -270,7 +270,25 @@ class RESTErrorCode(int, enums.Enum):
     """Unknown ban provided."""
 
     UNKNOWN_GUILD_TEMPLATE = 10_057
-    """Unknown guild template."""
+    """Unknown guild template provided."""
+
+    UNKNOWN_STICKER = 10_060
+    """Unknown sticker provided."""
+
+    UNKNOWN_INTERACTION = 10_062
+    """Unknown interaction provided."""
+
+    UNKNOWN_APPLICATION_COMMAND = 10_063
+    """Unknown application command provided."""
+
+    UNKNOWN_APPLICATION_COMMAND_PERMISSIONS = 10_066
+    """Unknown application command permissions provided."""
+
+    UNKNOWN_STAGE_INSTANCE = 10_067
+    """Unknown stage instance provided."""
+
+    UNKNOWN_GUILD_WELCOME_SCREEN = 10_069
+    """Unknown guild welcome screen provided."""
 
     EXPLICIT_CONTENT_BLOCKED = 20_009
     """Explicit content cannot be sent to the desired recipient(s)."""
@@ -281,8 +299,14 @@ class RESTErrorCode(int, enums.Enum):
     WRITE_LIMIT_HIT = 20_028
     """The global write limit on a channel has been hit."""
 
-    DISALLOWED_WORDS_IN_PUBLIC_STAGES = 20_031
-    """The stage channel contains disallowed words for public stages."""
+    DISALLOWED_WORDS_FOR_PUBLIC_STAGES = 20_031
+    """The guild contains disallowed words for public stages.
+
+    This may include guild name, guild description or channel names.
+    """
+
+    GUILD_PREMIUM_LEVEL_TOO_LOW = 20_035
+    """The guilds premium level is too low."""
 
     MAXIMUM_GUILDS = 30_001
     """Maximum number of guilds reached (100)."""
@@ -314,15 +338,24 @@ class RESTErrorCode(int, enums.Enum):
     MAXIMUM_ANIMATED_EMOJIS = 30_018
     """Maximum number of animated emojis reached."""
 
-    MAXIMUM_NUMBER_OF_SERVER_MEMBERS_REACHED = 30_019
-    """Maximum number of server members reached."""
+    MAXIMUM_NUMBER_OF_GUILD_MEMBERS_REACHED = 30_019
+    """Maximum number of guild members reached."""
 
     GUILD_ALREADY_HAS_TEMPLATE = 30_031
     """Guild already has a template."""
 
+    MAXIMUM_NUMBER_OF_THREAD_PARTICIPANTS_REACHED = 30_033
+    """Maximum number of thread participants reached."""
+
     MAXIMUM_BANS_FOR_NON_GUILD_MEMBERS = 30_035
     """Maximum number of bans for non-guild members reached."""
 
+    MAXIMUM_NUMBER_OF_STICKERS_REACHED = 30_037
+    """Maximum number of stickers reached."""
+
+    MAXIMUM_PRUNE_REQUESTS_REACHED = 30_040
+    """Maximum number of prune requests has been reached. Try again later."""
+
     REQUEST_TOO_LARGE = 40_005
     """Request too large. Try sending something smaller in size."""
 
@@ -401,6 +434,9 @@ class RESTErrorCode(int, enums.Enum):
     SYSTEM_OVERLOADED = 130_000
     """API resource is currently overloaded. Try again a little later."""
 
+    STAGE_ALREADY_OPEN = 150_006
+    """The stage channel is already open."""
+
 
 @attr.define(auto_exc=True, repr=False, weakref_slot=False)
 class HTTPResponseError(HTTPError):
@@ -409,7 +445,7 @@ class HTTPResponseError(HTTPError):
     url: str = attr.field()
     """The URL that produced this error message."""
 
-    status: typing.Union[int, http.HTTPStatus] = attr.field()
+    status: http.HTTPStatus = attr.field()
     """The HTTP status code for the response."""
 
     headers: data_binding.Headers = attr.field()
@@ -425,11 +461,13 @@ class HTTPResponseError(HTTPError):
     """The error code."""
 
     def __str__(self) -> str:
-        if isinstance(self.status, http.HTTPStatus):
-            name = self.status.name.replace("_", " ").title()
-            name_value = f"{name} {self.status.value}"
+        name = self.status.name.replace("_", " ").title()
+        name_value = f"{name} {self.status.value}"
+
+        if isinstance(self.code, RESTErrorCode) and self.code != RESTErrorCode.GENERAL_ERROR:
+            code_str = f" ({self.code.name})"
         else:
-            name_value = str(self.status).title()
+            code_str = ""
 
         if self.message:
             body = self.message
@@ -441,7 +479,7 @@ def __str__(self) -> str:
 
         chomped = len(body) > 200
 
-        return f"{name_value}: '{body[:200]}{'...' if chomped else ''}' for {self.url}"
+        return f"{name_value}:{code_str} '{body[:200]}{'...' if chomped else ''}' for {self.url}"
 
 
 @attr.define(auto_exc=True, repr=False, weakref_slot=False)
diff --git a/hikari/events/interaction_events.py b/hikari/events/interaction_events.py
index 2780c74e..11d169a3 100644
--- a/hikari/events/interaction_events.py
+++ b/hikari/events/interaction_events.py
@@ -23,7 +23,7 @@
 """Events fired for interaction related changes."""
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = [
+__all__: typing.List[str] = [
     "CommandEvent",
     "CommandCreateEvent",
     "CommandUpdateEvent",
diff --git a/hikari/files.py b/hikari/files.py
index 6a065aba..81c1e04d 100644
--- a/hikari/files.py
+++ b/hikari/files.py
@@ -24,7 +24,7 @@
 
 from __future__ import annotations
 
-__all__ = [
+__all__: typing.List[str] = [
     "ensure_path",
     "ensure_resource",
     "unwrap_bytes",
diff --git a/hikari/guilds.py b/hikari/guilds.py
index 4e5ef439..ba8ac61f 100644
--- a/hikari/guilds.py
+++ b/hikari/guilds.py
@@ -2991,8 +2991,11 @@ class RESTGuild(Guild):
     This will be `builtins.None` when creating a guild.
     """
 
-    max_presences: int = attr.field(eq=False, hash=False, repr=False)
-    """The maximum number of presences for the guild."""
+    max_presences: typing.Optional[int] = attr.field(eq=False, hash=False, repr=False)
+    """The maximum number of presences for the guild.
+
+    If `builtins.None`, then there is no limit.
+    """
 
     max_members: int = attr.field(eq=False, hash=False, repr=False)
     """The maximum number of members allowed in this guild."""
diff --git a/hikari/impl/entity_factory.py b/hikari/impl/entity_factory.py
index 1487bb3c..80e6ae74 100644
--- a/hikari/impl/entity_factory.py
+++ b/hikari/impl/entity_factory.py
@@ -61,9 +61,8 @@
 from hikari.internal import data_binding
 from hikari.internal import time
 
-_DEFAULT_MAX_PRESENCES: typing.Final[int] = 25000
-_LOGGER: typing.Final[logging.Logger] = logging.getLogger("hikari.entity_factory")
 _ValueT = typing.TypeVar("_ValueT")
+_LOGGER: typing.Final[logging.Logger] = logging.getLogger("hikari.entity_factory")
 
 
 def _with_int_cast(cast: typing.Callable[[int], _ValueT]) -> typing.Callable[[typing.Any], _ValueT]:
@@ -1372,10 +1371,7 @@ def deserialize_rest_guild(self, payload: data_binding.JSONObject) -> guild_mode
         max_members = int(payload["max_members"])
 
         raw_max_presences = payload["max_presences"]
-        if raw_max_presences is None:
-            max_presences = _DEFAULT_MAX_PRESENCES
-        else:
-            max_presences = int(raw_max_presences)
+        max_presences = int(raw_max_presences) if raw_max_presences is not None else None
 
         roles = {
             snowflakes.Snowflake(role["id"]): self.deserialize_role(role, guild_id=guild_fields.id)
diff --git a/hikari/impl/interaction_server.py b/hikari/impl/interaction_server.py
index f9b16d02..5f2fcc4e 100644
--- a/hikari/impl/interaction_server.py
+++ b/hikari/impl/interaction_server.py
@@ -23,7 +23,7 @@
 """Standard implementation of a REST based interactions server."""
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = ["InteractionServer"]
+__all__: typing.List[str] = ["InteractionServer"]
 
 import asyncio
 import logging
diff --git a/hikari/impl/rest_bot.py b/hikari/impl/rest_bot.py
index d3f5b53a..24d82c45 100644
--- a/hikari/impl/rest_bot.py
+++ b/hikari/impl/rest_bot.py
@@ -23,7 +23,7 @@
 """Standard implementations of a Interaction based REST-only bot."""
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = ["RESTBot"]
+__all__: typing.List[str] = ["RESTBot"]
 
 import asyncio
 import logging
diff --git a/hikari/internal/aio.py b/hikari/internal/aio.py
index 20bbdd63..b7731331 100644
--- a/hikari/internal/aio.py
+++ b/hikari/internal/aio.py
@@ -205,7 +205,7 @@ def get_or_make_loop() -> asyncio.AbstractEventLoop:
     # get_event_loop will error under oddly specific cases such as if set_event_loop has been called before even
     # if it was just called with None or if it's called on a thread which isn't the main Thread.
     try:
-        loop = asyncio.get_event_loop()
+        loop = asyncio.get_event_loop_policy().get_event_loop()
 
         # Closed loops cannot be re-used.
         if not loop.is_closed():
diff --git a/hikari/internal/ed25519.py b/hikari/internal/ed25519.py
index 0fc97f66..9119a09d 100644
--- a/hikari/internal/ed25519.py
+++ b/hikari/internal/ed25519.py
@@ -24,7 +24,7 @@
 
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = ["VerifyBuilderT", "VerifierT", "build_ed25519_verifier"]
+__all__: typing.List[str] = ["VerifyBuilderT", "VerifierT", "build_ed25519_verifier"]
 
 import typing
 
diff --git a/hikari/internal/mentions.py b/hikari/internal/mentions.py
index 825cb803..10e3216f 100644
--- a/hikari/internal/mentions.py
+++ b/hikari/internal/mentions.py
@@ -23,7 +23,7 @@
 """Utility functions used for managing mentions on Discord."""
 from __future__ import annotations
 
-__all__: typing.Sequence[str] = ["generate_allowed_mentions"]
+__all__: typing.List[str] = ["generate_allowed_mentions"]
 
 import typing
 
diff --git a/hikari/internal/time.py b/hikari/internal/time.py
index 20e85c60..316bdcba 100644
--- a/hikari/internal/time.py
+++ b/hikari/internal/time.py
@@ -87,13 +87,12 @@ def slow_iso8601_datetime_string_to_datetime(datetime_str: str) -> datetime.date
     return datetime.datetime.fromisoformat(datetime_str)
 
 
+fast_iso8601_datetime_string_to_datetime: typing.Optional[typing.Callable[[str], datetime.datetime]]
 try:
     # CISO8601 is around 600x faster than modules like dateutil, which is
     # going to be noticable on big bots where you are parsing hundreds of
     # thousands of "joined_at" fields on users on startup.
-    #
-    # ciso8601 doesn't have typing available, so ignore it.
-    import ciso8601  # type: ignore[import]
+    import ciso8601
 
     # Discord appears to actually use RFC-3339, which isn't a true ISO-8601 implementation,
     # but somewhat of a subset with some edge cases.
diff --git a/hikari/invites.py b/hikari/invites.py
index 4536fe98..cc5a9ebd 100644
--- a/hikari/invites.py
+++ b/hikari/invites.py
@@ -182,7 +182,7 @@ def make_splash_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optio
         )
 
     @property
-    def banner(self) -> typing.Optional[files.URL]:
+    def banner_url(self) -> typing.Optional[files.URL]:
         """Banner URL for the guild, if set."""
         return self.make_banner_url()
 
diff --git a/hikari/webhooks.py b/hikari/webhooks.py
index b4987c55..c9e5ccc1 100644
--- a/hikari/webhooks.py
+++ b/hikari/webhooks.py
@@ -543,19 +543,20 @@ def mention(self) -> str:
         return f"<@{self.id}>"
 
     @property
-    def avatar(self) -> files_.URL:
-        """URL for this webhook's custom avatar or default avatar.
+    def avatar_url(self) -> typing.Optional[files_.URL]:
+        """URL for this webhook's avatar, if set.
 
-        If the webhook has a custom avatar, a URL to this is returned. Otherwise
-        a URL to the default avatar is provided instead.
+        May be `builtins.None` if no avatar is set. In this case, you should use
+        `default_avatar_url` instead.
         """
-        return self.make_avatar_url() or self.default_avatar
+        return self.make_avatar_url()
 
     @property
-    def default_avatar(self) -> files_.URL:
-        """URL for this webhook's default avatar.
+    def default_avatar_url(self) -> files_.URL:
+        """Avatar URL for the user, if they have one set.
 
-        This is used if no avatar is set.
+        May be `builtins.None` if no custom avatar is set. In this case, you
+        should use `default_avatar_url` instead.
         """
         return routes.CDN_DEFAULT_USER_AVATAR.compile_to_file(
             urls.CDN_URL,
diff --git a/pipelines/mypy.nox.py b/pipelines/mypy.nox.py
index f2c1cedb..0502b3d8 100644
--- a/pipelines/mypy.nox.py
+++ b/pipelines/mypy.nox.py
@@ -35,7 +35,7 @@
 @nox.session(reuse_venv=True)
 def mypy(session: nox.Session) -> None:
     """Perform static type analysis on Python source code."""
-    session.install("-r", "requirements.txt", "-r", "dev-requirements.txt")
+    session.install("-r", "requirements.txt", "-r", "speedup-requirements.txt", "-r", "dev-requirements.txt")
 
     _generate_stubs(session)
 
@@ -46,7 +46,7 @@ def mypy(session: nox.Session) -> None:
 @nox.session(reuse_venv=True)
 def generate_stubs(session: nox.Session) -> None:
     """Generate the stubs for the package."""
-    session.install("-r", "requirements.txt", "-r", "dev-requirements.txt")
+    session.install("-r", "dev-requirements.txt")
     _generate_stubs(session)
 
 


Test patch:
diff --git a/tests/hikari/impl/test_entity_factory.py b/tests/hikari/impl/test_entity_factory.py
index 262e48b5..b209eb30 100644
--- a/tests/hikari/impl/test_entity_factory.py
+++ b/tests/hikari/impl/test_entity_factory.py
@@ -2411,7 +2411,7 @@ def test_deserialize_rest_guild_with_null_fields(self, entity_factory_impl):
         assert guild.widget_channel_id is None
         assert guild.system_channel_id is None
         assert guild.rules_channel_id is None
-        assert guild.max_presences is entity_factory._DEFAULT_MAX_PRESENCES
+        assert guild.max_presences is None
         assert guild.vanity_url_code is None
         assert guild.description is None
         assert guild.banner_hash is None
diff --git a/tests/hikari/impl/test_rest_bot.py b/tests/hikari/impl/test_rest_bot.py
index 91f67cdb..26078818 100644
--- a/tests/hikari/impl/test_rest_bot.py
+++ b/tests/hikari/impl/test_rest_bot.py
@@ -297,7 +297,7 @@ def test_run(self, mock_rest_bot):
             ssl_context=mock_context,
         )
         mock_rest_bot.join.assert_awaited_once()
-        assert asyncio.get_event_loop().is_closed() is False
+        assert asyncio.get_event_loop_policy().get_event_loop().is_closed() is False
 
     def test_run_when_asyncio_debug(self, mock_rest_bot):
         mock_rest_bot.start = mock.Mock()
diff --git a/tests/hikari/internal/test_aio.py b/tests/hikari/internal/test_aio.py
index aad61eb1..8cf1eca4 100644
--- a/tests/hikari/internal/test_aio.py
+++ b/tests/hikari/internal/test_aio.py
@@ -398,7 +398,7 @@ def test_get_or_make_loop_handles_runtime_error():
 
         new_event_loop.assert_called_once_with()
 
-    assert asyncio.get_event_loop() is mock_loop
+    assert asyncio.get_event_loop_policy().get_event_loop() is mock_loop
 
 
 def test_get_or_make_loop_handles_closed_loop():
@@ -410,4 +410,4 @@ def test_get_or_make_loop_handles_closed_loop():
 
         new_event_loop.assert_called_once_with()
 
-    assert asyncio.get_event_loop() is mock_loop
+    assert asyncio.get_event_loop_policy().get_event_loop() is mock_loop
diff --git a/tests/hikari/test_errors.py b/tests/hikari/test_errors.py
index 0c067efe..875dfcee 100644
--- a/tests/hikari/test_errors.py
+++ b/tests/hikari/test_errors.py
@@ -75,19 +75,29 @@ def test_str(self, error):
 class TestHTTPResponseError:
     @pytest.fixture()
     def error(self):
-        return errors.HTTPResponseError("https://some.url", http.HTTPStatus.BAD_REQUEST, {}, "raw body")
+        return errors.HTTPResponseError(
+            "https://some.url",
+            http.HTTPStatus.BAD_REQUEST,
+            {},
+            "raw body",
+            "message",
+            errors.RESTErrorCode.UNKNOWN_GUILD,
+        )
 
     def test_str(self, error):
-        assert str(error) == "Bad Request 400: 'raw body' for https://some.url"
+        assert str(error) == "Bad Request 400: (UNKNOWN_GUILD) 'message' for https://some.url"
+
+    def test_str_when_message_is_None(self, error):
+        error.message = None
+        assert str(error) == "Bad Request 400: (UNKNOWN_GUILD) 'raw body' for https://some.url"
 
-    def test_str_when_status_is_not_HTTPStatus(self, error):
-        error.status = "SOME STATUS"
-        assert str(error) == "Some Status: 'raw body' for https://some.url"
+    def test_str_when_code_is_GENERAL_ERROR(self, error):
+        error.code = errors.RESTErrorCode.GENERAL_ERROR
+        assert str(error) == "Bad Request 400: 'message' for https://some.url"
 
-    def test_str_when_message_is_not_None(self, error):
-        error.status = "SOME STATUS"
-        error.message = "Some message"
-        assert str(error) == "Some Status: 'Some message' for https://some.url"
+    def test_str_when_code_is_int(self, error):
+        error.code = 100
+        assert str(error) == "Bad Request 400: 'message' for https://some.url"
 
 
 class TestBadRequestError:
diff --git a/tests/hikari/test_webhooks.py b/tests/hikari/test_webhooks.py
index 3feeda0f..cdc69a31 100644
--- a/tests/hikari/test_webhooks.py
+++ b/tests/hikari/test_webhooks.py
@@ -194,16 +194,11 @@ def test_str_when_name_is_None(self, webhook):
     def test_mention_property(self, webhook):
         assert webhook.mention == "<@987654321>"
 
-    def test_avatar_property(self, webhook):
-        assert webhook.avatar == webhook.make_avatar_url()
+    def test_avatar_url_property(self, webhook):
+        assert webhook.avatar_url == webhook.make_avatar_url()
 
-    def test_avatar_property_when_default(self, webhook):
-        webhook.avatar_hash = None
-
-        assert webhook.avatar == webhook.default_avatar
-
-    def test_default_avatar(self, webhook):
-        assert webhook.default_avatar.url == "https://cdn.discordapp.com/embed/avatars/0.png"
+    def test_default_avatar_url(self, webhook):
+        assert webhook.default_avatar_url.url == "https://cdn.discordapp.com/embed/avatars/0.png"
 
     def test_make_avatar_url(self, webhook):
         result = webhook.make_avatar_url(ext="jpeg", size=2048)