Skip to content

Commit

Permalink
remove old hack
Browse files Browse the repository at this point in the history
  • Loading branch information
willmcgugan committed Sep 7, 2024
1 parent c581182 commit 03ad3af
Show file tree
Hide file tree
Showing 18 changed files with 754 additions and 724 deletions.
59 changes: 5 additions & 54 deletions src/textual/_context.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from __future__ import annotations

import weakref
from contextvars import ContextVar, Token
from typing import TYPE_CHECKING, Callable, Generic, TypeVar, overload
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Callable, TypeVar

if TYPE_CHECKING:
from .app import App
Expand All @@ -19,54 +18,8 @@ class NoActiveAppError(RuntimeError):
DefaultType = TypeVar("DefaultType")


class ContextDefault:
pass


_context_default = ContextDefault()


class TextualContextVar(Generic[ContextVarType]):
"""Like ContextVar but doesn't hold on to references."""

def __init__(self, name: str) -> None:
self._context_var: ContextVar[weakref.ReferenceType[ContextVarType]] = (
ContextVar(name)
)

@overload
def get(self) -> ContextVarType: ...

@overload
def get(self, default: DefaultType) -> ContextVarType | DefaultType: ...

def get(
self, default: DefaultType | ContextDefault = _context_default
) -> ContextVarType | DefaultType:
try:
value_ref = self._context_var.get()
except LookupError:
if isinstance(default, ContextDefault):
raise
return default
value = value_ref()
if value is None:
if isinstance(default, ContextDefault):
raise LookupError(value)
return default
return value

def set(self, value: ContextVarType) -> object:
return self._context_var.set(weakref.ref(value))

def reset(self, token: Token[weakref.ReferenceType[ContextVarType]]) -> None:
self._context_var.reset(token)


active_app: TextualContextVar["App[object]"] = TextualContextVar("active_app")
active_message_pump: TextualContextVar["MessagePump"] = TextualContextVar(
"active_message_pump"
)
active_app: ContextVar["App[Any]"] = ContextVar("active_app")
active_message_pump: ContextVar["MessagePump"] = ContextVar("active_message_pump")

prevent_message_types_stack: ContextVar[list[set[type[Message]]]] = ContextVar(
"prevent_message_types_stack"
Expand All @@ -75,7 +28,5 @@ def reset(self, token: Token[weakref.ReferenceType[ContextVarType]]) -> None:
"visible_screen_stack"
)
"""A stack of visible screens (with background alpha < 1), used in the screen render process."""
message_hook: TextualContextVar[Callable[[Message], None]] = TextualContextVar(
"message_hook"
)
message_hook: ContextVar[Callable[[Message], None]] = ContextVar("message_hook")
"""A callable that accepts a message. Used by App.run_test."""
Loading

0 comments on commit 03ad3af

Please sign in to comment.