Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Make responses generic #1534

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

Closed
wants to merge 1 commit into from
Closed

Make responses generic #1534

wants to merge 1 commit into from

Conversation

cglacet
Copy link

@cglacet cglacet commented Mar 3, 2022

I think this might be usefull to allow (static) typechecking route responses.

For now responses content type is typing.Any, instead we could use generics.
The following doesn't yield any error:

from typing import TypedDict

from starlette.requests import Request
from starlette.responses import JSONResponse

class Coordinates(TypedDict):
    latitude: float
    longitude: float

async def valid_route(request: Request) -> JSONResponse[Coordinates]: 
    return JSONResponse({'latitude': 1, 'longitude': 2})

While this would raise a type error ("dict[str, int | str]" is incompatible with "Coordinates"):

async def invalid_route(request: Request) -> JSONResponse[Coordinates]: 
    return JSONResponse({'latitude': 1, 'longitude': 'douze'})

I know many people are using FastAPI with pydantic, but I needed to have this so I though maybe I'm not alone.

Maybe the same could be done for responses .json()?

@Kludex
Copy link
Member

Kludex commented Apr 11, 2022

@euri10 If I'm not mistaken, you were interested on something related to this... But I'm not sure...

@Kludex Kludex added typing Type annotations or mypy issues feature New feature or request labels Apr 11, 2022
@Kludex
Copy link
Member

Kludex commented Apr 21, 2022

@cglacet Thanks for the PR. I think this content is relevant, but I think a discussion about it should be created first. If you're still interested in this, would you mind creating one?

Closing this so we can have a discussion.

@Kludex Kludex closed this Apr 21, 2022
@Kludex
Copy link
Member

Kludex commented Dec 22, 2023

When python/mypy#14851 gets in, we can implement it in Starlette.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request typing Type annotations or mypy issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants