Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Comments

Add param functions, to override types, to make mypy happy#226

Merged
tiangolo merged 1 commit intomasterfrom
override-param-types
May 15, 2019
Merged

Add param functions, to override types, to make mypy happy#226
tiangolo merged 1 commit intomasterfrom
override-param-types

Conversation

@tiangolo
Copy link
Member

✨ Add param functions, to override types, to makemypy happy.

This would solve#219 and other cases ofmypy complaining about the default types.

Simple solution

The simplest approach would be to makemypy ignore the types in those parameters, using comments with# type: ignore like in:

fromfastapiimportFastAPI,Path,Queryapp=FastAPI()@app.get("/items/{item_id}")asyncdefread_items(# type: ignoreitem_id:int=Path(...,title="The ID of the item to get"),q:str=Query(None,alias="item-query"),  ):results= {"item_id":item_id}ifq:results.update({"q":q})returnresults

Drawback

But asking all the users to add comments to ignore type checks each time they use these classes would be difficult and cumbersome (for end users/developers).

Reason

The issue is thatmypy is right, from the typing point of view. Putting an instance ofQuery as the "default value" of a parameter with typestr is not really correct (from the typing point of view).

But here in FastAPI we are "hacking" the typing system, and extending its use to the extreme (which has proven to work really well for many users/use-cases). Thepath operation function is only called by FastAPI (not by the user or any other code), and FastAPI makes sure to pass the correct type, those classes are only for meta-information, used by FastAPI.

Alternatives

I tried overriding the type declaration of the parameter classes, but there's no way to achieve that.

Then I tried adding a typing stub (parameters.pyi), but although it removedmypy errors, there where other errors in places used by FastAPI internally.

And then, by relaxing the type declarations to avoid the internal errors, the type hints of those parameters were also lost for final users.

There's a lot of work (and code) there just to have completion for all those parameters in classes... One of the main objectives is for FastAPI to be as comfortable for final developers as possible, even if that is at the expense of the developers of the library itself (me and the community that submits PRs 😁 ).

Final solution

Here's the solution. We can't override the type declaration of a class (the class itself).

But we can override the return type declaration of a function.

So, I converted all these parameter classes exposed by FastAPI (Depends,Query,File, etc) to functions. But then, as the function is actually called when the code is run and FastAPI needs to inspect it afterwards when the app is running, each of these functions returns the original class instances.

So, the default values of the parameters are actually those classes, and can be checked by the rest of the FastAPI code (dependencies, etc).

Victor-Savu, cepbuch, phillipuniverse, and u-ishii reacted with thumbs up emoji
@tiangolotiangolo changed the title✨ Add param functions, to override types, to make mypy happyAdd param functions, to override types, to make mypy happyMay 14, 2019
@codecov
Copy link

codecovbot commentedMay 14, 2019
edited
Loading

Codecov Report

Merging#226 intomaster willnot change coverage.
The diff coverage is100%.

Impacted file tree graph

@@          Coverage Diff          @@##           master   #226   +/-   ##=====================================  Coverage     100%   100%           =====================================  Files         170    171    +1       Lines        4122   4142   +20     =====================================+ Hits         4122   4142   +20
Impacted FilesCoverage Δ
fastapi/dependencies/utils.py100% <100%> (ø)⬆️
fastapi/__init__.py100% <100%> (ø)⬆️
fastapi/param_functions.py100% <100%> (ø)

Continue to review full report at Codecov.

Legend -Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing data
Powered byCodecov. Last update5f13b53...2200b3d. Read thecomment docs.

@Victor-Savu
Copy link

👍 This is a very nice use ofAny! It is an elegant solution. Kudos!

Thank you for placing the emphasis on user experience!

tiangolo reacted with thumbs up emojitiangolo reacted with hooray emoji

@tiangolotiangolo merged commitca27317 intomasterMay 15, 2019
@tiangolotiangolo deleted the override-param-types branchMay 15, 2019 17:25
@tiangolo
Copy link
MemberAuthor

Thanks@Victor-Savu ! 😄 🎉

lmignon pushed a commit to acsone/fastapi that referenced this pull requestSep 19, 2024
Signed-off-by simahawk
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

No reviews

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@tiangolo@Victor-Savu

[8]ページ先頭

©2009-2026 Movatter.jp