Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to make Request generic over State #2218

Closed
wants to merge 1 commit into from

Conversation

adriangb
Copy link
Member

@adriangb adriangb commented Jul 20, 2023

#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.

@adriangb
Copy link
Member Author

@Kludex any idea how to get this to work nicely with mypy?

@Kludex
Copy link
Member

Kludex commented Jul 20, 2023

@Kludex any idea how to get this to work nicely with mypy?

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.)

@Kludex
Copy link
Member

Kludex commented Aug 29, 2023

I've created python/typing#1457.

@michaeloliverx
Copy link
Member

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)]

@Kludex
Copy link
Member

Kludex commented Dec 16, 2023

I'll close this, since the Python type system still doesn't support this.

@Kludex Kludex closed this Dec 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants