Try to make Request generic over State#2218
Closed
adriangb wants to merge 1 commit intoKludex:masterfrom
Closed
Conversation
Contributor
Author
|
@Kludex any idea how to get this to work nicely with mypy? |
Owner
I think I have some comments around about it. I'll look later, and share it here. (It maybe in our WhatsApp conversation... I'll check.) |
Owner
|
I've created python/typing#1457. |
|
On an semi related side note I hacked around this in FastAPI by doing this: from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Annotated, TypedDict, cast
from fastapi import Depends, FastAPI, Request
class State(TypedDict):
foo: str
bar: str
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[State, None]:
...
async def get_state(request: Request) -> State:
return cast(State, request.state._state)
StateDependency = Annotated[State, Depends(get_state)] |
Owner
|
I'll close this, since the Python type system still doesn't support this.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
#2065 (comment)
TODO: how do we let users at runtime customize the state creation function? Currently, Starlette creates the Request object so it can't be as simple as a constructor parameter. For FastAPI I suppose it could introspect the type hints to get the generic argument.