Skip to content

feat: Replaced useless cached_property with property and moved to functools.cached_property #2769

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

Open
wants to merge 4 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,12 +602,12 @@ def _get_member(self, user_id: int) -> Member | User | None:
def __repr__(self) -> str:
return f"<AuditLogEntry id={self.id} action={self.action} user={self.user!r}>"

@utils.cached_property
@property
def created_at(self) -> datetime.datetime:
"""Returns the entry's creation time in UTC."""
return utils.snowflake_time(self.id)

@utils.cached_property
@property
def target(
self,
) -> (
Expand All @@ -631,24 +631,24 @@ def target(
else:
return converter(self._target_id)

@utils.cached_property
@property
def category(self) -> enums.AuditLogActionCategory:
"""The category of the action, if applicable."""
return self.action.category

@utils.cached_property
@property
def changes(self) -> AuditLogChanges:
"""The list of changes this entry has."""
obj = AuditLogChanges(self, self._changes, state=self._state)
del self._changes
return obj

@utils.cached_property
@property
def before(self) -> AuditLogDiff:
"""The target's prior state."""
return self.changes.before

@utils.cached_property
@property
def after(self) -> AuditLogDiff:
"""The target's subsequent state."""
return self.changes.after
Expand Down
4 changes: 2 additions & 2 deletions discord/automod.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,12 +416,12 @@ def __repr__(self) -> str:
def __str__(self) -> str:
return self.name

@cached_property
@property
def guild(self) -> Guild | None:
"""The guild this rule belongs to."""
return self._state._get_guild(self.guild_id)

@cached_property
@property
def creator(self) -> Member | None:
"""The member who created this rule."""
if self.guild is None:
Expand Down
45 changes: 21 additions & 24 deletions discord/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,25 @@
from discord.webhook.async_ import Webhook

if TYPE_CHECKING:
from typing import Awaitable, Callable

from typing_extensions import ParamSpec

import discord
from .. import Bot
from ..state import ConnectionState
from ..voice_client import VoiceClient

from .core import ApplicationCommand, Option
from ..interactions import InteractionChannel
from .. import Bot
from ..client import ClientUser
from ..cog import Cog
from ..guild import Guild
from ..interactions import InteractionChannel
from ..member import Member
from ..message import Message
from ..user import User
from ..permissions import Permissions
from ..client import ClientUser

from ..cog import Cog
from ..state import ConnectionState
from ..user import User
from ..voice_client import VoiceClient
from ..webhook import WebhookMessage

from typing import Callable, Awaitable

from ..utils import cached_property
from .core import ApplicationCommand, Option

T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
Expand Down Expand Up @@ -136,53 +133,53 @@ async def invoke(
"""
return await command(self, *args, **kwargs)

@cached_property
@property
def channel(self) -> InteractionChannel | None:
"""Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]:
Returns the channel associated with this context's command. Shorthand for :attr:`.Interaction.channel`.
"""
return self.interaction.channel

@cached_property
@property
def channel_id(self) -> int | None:
"""Returns the ID of the channel associated with this context's command.
Shorthand for :attr:`.Interaction.channel_id`.
"""
return self.interaction.channel_id

@cached_property
@property
def guild(self) -> Guild | None:
"""Returns the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild`.
"""
return self.interaction.guild

@cached_property
@property
def guild_id(self) -> int | None:
"""Returns the ID of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild_id`.
"""
return self.interaction.guild_id

@cached_property
@property
def locale(self) -> str | None:
"""Returns the locale of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.locale`.
"""
return self.interaction.locale

@cached_property
@property
def guild_locale(self) -> str | None:
"""Returns the locale of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild_locale`.
"""
return self.interaction.guild_locale

@cached_property
@property
def app_permissions(self) -> Permissions:
return self.interaction.app_permissions

@cached_property
@property
def me(self) -> Member | ClientUser | None:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message
Expand All @@ -194,14 +191,14 @@ def me(self) -> Member | ClientUser | None:
else self.bot.user
)

@cached_property
@property
def message(self) -> Message | None:
"""Returns the message sent with this context's command.
Shorthand for :attr:`.Interaction.message`, if applicable.
"""
return self.interaction.message

@cached_property
@property
def user(self) -> Member | User:
"""Returns the user that sent this context's command.
Shorthand for :attr:`.Interaction.user`.
Expand All @@ -220,7 +217,7 @@ def voice_client(self) -> VoiceClient | None:

return self.interaction.guild.voice_client

@cached_property
@property
def response(self) -> InteractionResponse:
"""Returns the response object associated with this context's command.
Shorthand for :attr:`.Interaction.response`.
Expand Down
8 changes: 4 additions & 4 deletions discord/ext/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,28 +283,28 @@ def cog(self) -> Cog | None:
return None
return self.command.cog

@discord.utils.cached_property
@property
def guild(self) -> Guild | None:
"""Returns the guild associated with this context's command.
None if not available.
"""
return self.message.guild

@discord.utils.cached_property
@property
def channel(self) -> MessageableChannel:
"""Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel

@discord.utils.cached_property
@property
def author(self) -> User | Member:
"""Union[:class:`~discord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author

@discord.utils.cached_property
@property
def me(self) -> Member | ClientUser:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message
Expand Down
3 changes: 2 additions & 1 deletion discord/onboarding.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@

from __future__ import annotations

from functools import cached_property
from typing import TYPE_CHECKING, Any

from .enums import OnboardingMode, PromptType, try_enum
from .partial_emoji import PartialEmoji
from .utils import MISSING, cached_property, generate_snowflake, get
from .utils import MISSING, generate_snowflake, get

if TYPE_CHECKING:
from .abc import Snowflake
Expand Down
3 changes: 2 additions & 1 deletion discord/poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from __future__ import annotations

import datetime
from functools import cached_property
from typing import TYPE_CHECKING, Any

from . import utils
Expand Down Expand Up @@ -358,7 +359,7 @@ def __init__(
self._expiry = None
self._message = None

@utils.cached_property
@cached_property
def expiry(self) -> datetime.datetime | None:
"""An aware datetime object that specifies the date and time in UTC when the poll will end."""
return utils.parse_time(self._expiry)
Expand Down
19 changes: 0 additions & 19 deletions discord/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,6 @@ def __repr__(self) -> str:
# error.
MissingField = field(default_factory=lambda: MISSING)


class _cached_property:
def __init__(self, function):
self.function = function
self.__doc__ = getattr(function, "__doc__")

def __get__(self, instance, owner):
if instance is None:
return self

value = self.function(instance)
setattr(instance, self.function.__name__, value)

return value


if TYPE_CHECKING:
from typing_extensions import ParamSpec

Expand All @@ -150,12 +134,9 @@ def __get__(self, instance, owner):
class _RequestLike(Protocol):
headers: Mapping[str, Any]

cached_property = property

P = ParamSpec("P")

else:
cached_property = _cached_property
AutocompleteContext = Any
OptionChoice = Any

Expand Down
17 changes: 0 additions & 17 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@

from discord.utils import (
MISSING,
_cached_property,
_parse_ratelimit_header,
_unique,
async_all,
Expand Down Expand Up @@ -80,22 +79,6 @@ def test_temporary():
# assert repr(MISSING) == '...'
#
#
# def test_cached_property() -> None:
# class Test:
# def __init__(self, x: int):
# self.x = x
#
# @_cached_property
# def foo(self) -> int:
# self.x += 1
# return self.x
#
# t = Test(0)
# assert isinstance(_cached_property.__get__(_cached_property(None), None, None), _cached_property)
# assert t.foo == 1
# assert t.foo == 1
#
#
# def test_find_get() -> None:
# class Obj:
# def __init__(self, value: int):
Expand Down