From b11e6d565d4a84b66446560ba733a95d12d43f1a Mon Sep 17 00:00:00 2001 From: Winston Chang Date: Tue, 5 Mar 2024 09:46:32 -0600 Subject: [PATCH] Use cast() for asgiref types only when type checking --- shiny/_autoreload.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/shiny/_autoreload.py b/shiny/_autoreload.py index b9c3646dd..b77fec6fe 100644 --- a/shiny/_autoreload.py +++ b/shiny/_autoreload.py @@ -104,7 +104,9 @@ def __init__( ) # The starlette types and the asgiref types are compatible, but we'll use the # latter internally. See the note in the __call__ method for more details. - self.app = cast(ASGI3Application, app) + if TYPE_CHECKING: + app = cast(ASGI3Application, app) + self.app = app ws_url = autoreload_url() self.script = ( f""" @@ -125,13 +127,15 @@ async def __call__( # more rigorous. In the call interface, we accept both types for compatibility # with both. But internally we'll use the more rigorous types. # See https://github.com/encode/starlette/blob/39dccd9/docs/middleware.md#type-annotations - scope = cast(Scope, scope) - receive_casted = cast(ASGIReceiveCallable, receive) - send_casted = cast(ASGISendCallable, send) + if TYPE_CHECKING: + scope = cast(Scope, scope) + receive = cast(ASGIReceiveCallable, receive) + send = cast(ASGISendCallable, send) + if scope["type"] != "http": - return await self.app(scope, receive_casted, send_casted) + return await self.app(scope, receive, send) if scope["path"] != "/" or len(self.script) == 0: - return await self.app(scope, receive_casted, send_casted) + return await self.app(scope, receive, send) def mangle_callback(body: bytes) -> tuple[bytes, bool]: if b"" in body: @@ -139,8 +143,8 @@ def mangle_callback(body: bytes) -> tuple[bytes, bool]: else: return (body, False) - mangler = ResponseMangler(send_casted, mangle_callback) - await self.app(scope, receive_casted, mangler.send) + mangler = ResponseMangler(send, mangle_callback) + await self.app(scope, receive, mangler.send) # PARENT PROCESS ------------------------------------------------------------