Skip to content

Comments

Try to make Request generic over State#2218

Closed
adriangb wants to merge 1 commit intoKludex:masterfrom
adriangb:generic-request
Closed

Try to make Request generic over State#2218
adriangb wants to merge 1 commit intoKludex:masterfrom
adriangb:generic-request

Conversation

@adriangb
Copy link
Contributor

@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
Contributor Author

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

@Kludex
Copy link
Owner

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
Owner

Kludex commented Aug 29, 2023

I've created python/typing#1457.

@michaeloliverx
Copy link

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
Owner

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