Skip to content

Make request.state generic #3005

@Kludex

Description

@Kludex

Discussed in #2562

Originally posted by patrick91 April 3, 2024
Hi there!

I was playing around with request.state, and I was wondering if we could make it generic, so that users can get better autocomplete on it (and maybe a bit of type safety too).

The way this would work is where you accept a Request you could also do Request[MyStateType], and request.state would be of type MyStateType

I think we can implement this in a backwards compatible way if we use TypeVar from typing extensions with a default value of any, like this:

from typing import Any
from typing_extensions import TypeVar

RequestState = TypeVar("RequestState", default=Any)  # this could also be `State`

This means that any current code wouldn't throw an error, and power users could type the state var 😊

The only issue I see at the moment is that State is a wrapper on a dict, but doesn't provide getitem, and my assumption is that types for State would be TypedDicts 😊 but is should be easy to add support for that. But I'm also saying this without knowing the reason why the state is a class on top of a dict, so I might be wrong :D

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions