From d826f4f3a8d4d97d24499f5de5c51e11e640e98f Mon Sep 17 00:00:00 2001 From: Mikey <8661717+sgtlaggy@users.noreply.github.com> Date: Tue, 9 Aug 2022 05:37:46 -0700 Subject: [PATCH] Change ui.Select.values to a ContextVar to avoid race conditions --- discord/ui/select.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/discord/ui/select.py b/discord/ui/select.py index 852d3ad07..8eb6f98b8 100644 --- a/discord/ui/select.py +++ b/discord/ui/select.py @@ -24,6 +24,7 @@ DEALINGS IN THE SOFTWARE. from __future__ import annotations from typing import List, Literal, Optional, TYPE_CHECKING, Tuple, TypeVar, Callable, Union +from contextvars import ContextVar import inspect import os @@ -53,6 +54,8 @@ if TYPE_CHECKING: V = TypeVar('V', bound='View', covariant=True) +selected_values: ContextVar[Optional[List[str]]] = ContextVar('selected_values', default=None) + class Select(Item[V]): """Represents a UI select menu. @@ -108,7 +111,6 @@ class Select(Item[V]): row: Optional[int] = None, ) -> None: super().__init__() - self._selected_values: List[str] = [] self._provided_custom_id = custom_id is not MISSING custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id if not isinstance(custom_id, str): @@ -260,7 +262,8 @@ class Select(Item[V]): @property def values(self) -> List[str]: """List[:class:`str`]: A list of values that have been selected by the user.""" - return self._selected_values + values = selected_values.get() + return values if values is not None else [] @property def width(self) -> int: @@ -273,7 +276,7 @@ class Select(Item[V]): self._underlying = component def _refresh_state(self, data: MessageComponentInteractionData) -> None: - self._selected_values = data.get('values', []) + selected_values.set(data.get('values', [])) @classmethod def from_component(cls, component: SelectMenu) -> Self: