Skip to content

Commit 55fdfdd

Browse files
authored
Use cast() for asgiref types only when type checking (#1190)
1 parent 0b170d3 commit 55fdfdd

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

shiny/_autoreload.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,9 @@ def __init__(
104104
)
105105
# The starlette types and the asgiref types are compatible, but we'll use the
106106
# latter internally. See the note in the __call__ method for more details.
107-
self.app = cast(ASGI3Application, app)
107+
if TYPE_CHECKING:
108+
app = cast(ASGI3Application, app)
109+
self.app = app
108110
ws_url = autoreload_url()
109111
self.script = (
110112
f""" <script src="__shared/shiny-autoreload.js" data-ws-url="{html.escape(ws_url)}"></script>
@@ -125,22 +127,24 @@ async def __call__(
125127
# more rigorous. In the call interface, we accept both types for compatibility
126128
# with both. But internally we'll use the more rigorous types.
127129
# See https://github.com/encode/starlette/blob/39dccd9/docs/middleware.md#type-annotations
128-
scope = cast(Scope, scope)
129-
receive_casted = cast(ASGIReceiveCallable, receive)
130-
send_casted = cast(ASGISendCallable, send)
130+
if TYPE_CHECKING:
131+
scope = cast(Scope, scope)
132+
receive = cast(ASGIReceiveCallable, receive)
133+
send = cast(ASGISendCallable, send)
134+
131135
if scope["type"] != "http":
132-
return await self.app(scope, receive_casted, send_casted)
136+
return await self.app(scope, receive, send)
133137
if scope["path"] != "/" or len(self.script) == 0:
134-
return await self.app(scope, receive_casted, send_casted)
138+
return await self.app(scope, receive, send)
135139

136140
def mangle_callback(body: bytes) -> tuple[bytes, bool]:
137141
if b"</head>" in body:
138142
return (body.replace(b"</head>", self.script, 1), True)
139143
else:
140144
return (body, False)
141145

142-
mangler = ResponseMangler(send_casted, mangle_callback)
143-
await self.app(scope, receive_casted, mangler.send)
146+
mangler = ResponseMangler(send, mangle_callback)
147+
await self.app(scope, receive, mangler.send)
144148

145149

146150
# PARENT PROCESS ------------------------------------------------------------

0 commit comments

Comments
 (0)