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

Fix type checking issue withmodel_fields andmodel_computed_fields#10911

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
sydney-runkle merged 4 commits intomainfromfix-type-checking-issue-model-fields
Nov 21, 2024

Conversation

sydney-runkle
Copy link
Contributor

vfazio reacted with thumbs up emoji
@github-actionsgithub-actionsbot added the relnotes-fixUsed for bugfixes. labelNov 20, 2024
@cloudflare-workers-and-pagesCloudflare Workers and Pages
Copy link

cloudflare-workers-and-pagesbot commentedNov 20, 2024
edited
Loading

Deploying pydantic-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit:60522af
Status: ✅  Deploy successful!
Preview URL:https://88b7606a.pydantic-docs.pages.dev
Branch Preview URL:https://fix-type-checking-issue-mode.pydantic-docs.pages.dev

View logs

@sydney-runklesydney-runkle added the topic-type checkingRelated to type checking labelNov 20, 2024
@codspeed-hqCodSpeed HQ
Copy link

codspeed-hqbot commentedNov 20, 2024
edited
Loading

CodSpeed Performance Report

Merging#10911 willnot alter performance

Comparingfix-type-checking-issue-model-fields (60522af) withmain (b985365)

Summary

✅ 46 untouched benchmarks

@github-actionsGitHub Actions
Copy link
Contributor

github-actionsbot commentedNov 20, 2024
edited
Loading

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  pydantic
  main.py
Project Total 

This report was generated bypython-coverage-comment-action

@Viicos
Copy link
Member

Viicos commentedNov 21, 2024
edited
Loading

We are hitting undefined behavior between pyright and mypy here, when a property is defined both on the metaclass and the class itself. I think it's a bit unfortunate to havemodel_fields typed as a class variable, because it won't emit deprecation warnings here. Here is an alternative approach:

  • Until V3, we use the following descriptor defined onBaseModel (not the metaclass):

Code sample inpyright playground

importwarningsfromtypingimportCallable,Generic,TypeVar,overloadfromtyping_extensionsimportdeprecatedfrompydantic.warningsimportPydanticDeprecatedSince211ModelT=TypeVar('ModelT',bound='BaseModel')R=TypeVar('R')classclassonlyproperty(Generic[ModelT,R]):def__init__(self,fget:Callable[[type[ModelT]],R],/)->None:self.fget=fget@overloaddef__get__(self,instance:None,owner:type[ModelT])->R: ...@overload@deprecated("Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3.",category=None,    )def__get__(self,instance:ModelT,owner:type[ModelT])->R: ...def__get__(self,instance:ModelT|None,owner:type[ModelT])->R:ifinstanceisnotNone:warnings.warn("Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3.",category=PydanticDeprecatedSince211,            )returnself.fget(owner)classBaseModel:@classonlyproperty@classmethoddefmodel_fields(cls)->dict[str,str]:        ...BaseModel.model_fieldsBaseModel().model_fields# type checker error

pyright will emit an error, and mypywill probablybe able to do so soon implements it in 1.14.

  • In V3, we remove theclassonlyproperty helper and themodel_fields fromBaseModel to move it back to the model metaclass, as it is currently.

WDYT?

@ViicosViicos mentioned this pull requestNov 21, 2024
36 tasks
@sydney-runkle
Copy link
ContributorAuthor

@Viicos,

Interesting idea. 2 reservations I have about this:

  • The reason we included themodel_fields property onBaseModel in the first place was for backwards compatibility - folks sometimes accessmodel_fields on aBaseModel instance. Thus, I think decorating with theclassonlyproperty is a bit misleading.

I sort of poorly explained this in a comment:

# TODO: V3 - remove `model_fields` and `model_computed_fields` properties from the `BaseModel` class - they should only# be accessible on the model class, not on instances. We have these purely for backwards compatibility with Pydantic <v2.10.
  • Class properties aren't supported by Python, so I think this might be doing a bit more type hacking / jumping through hoops than we really should be doing?

@Viicos
Copy link
Member

Viicos commentedNov 21, 2024
edited
Loading

  • Thus, I think decorating with theclassonlyproperty is a bit misleading.

The naming of the decorator can be improved, but with this approach, accessing the propertydoes work at runtime. However, it will emit a runtime deprecation warning and a type checker error/warning

  • Class properties aren't supported by Python, so I think this might be doing a bit more type hacking / jumping through hoops than we really should be doing?

Well the usage of the descriptor can feel a bit too much for such a small use case, but descriptor support is implemented by all major type checkers and this seems to be the only viable approach to emit a deprecation warning. I'm a bit worried that in V3 this will come as a surprise, because we currently don't emit anything (as an example, SQLModelrelies on this)

@sydney-runkle
Copy link
ContributorAuthor

Yeah, fair point.

What if:

  • For v2.10, we go with the approach on this PR
  • For v2.11, we go with your approach (I don't want to introduce a deprecation warning in a patch release 😓)

@Viicos
Copy link
Member

Sounds good, could you please add some tests in thetypechecking folder? Probably inbase_model.py.

sydney-runkle reacted with thumbs up emoji

@sydney-runkle
Copy link
ContributorAuthor

Oh so odd, I think I have them locally but didn't push...

sydney-runkleand others added2 commitsNovember 21, 2024 09:30
Co-authored-by: Victorien <65306057+Viicos@users.noreply.github.com>
Copy link
Member

@ViicosViicos left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

thanks for adding the tests

sydney-runkle reacted with heart emoji
@sydney-runklesydney-runkle merged commit9915abf intomainNov 21, 2024
54 checks passed
@sydney-runklesydney-runkle deleted the fix-type-checking-issue-model-fields branchNovember 21, 2024 15:02
sydney-runkle added a commit that referenced this pull requestNov 22, 2024
…s` (#10911)Co-authored-by: Victorien <65306057+Viicos@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@ViicosViicosViicos approved these changes

Assignees
No one assigned
Labels
relnotes-fixUsed for bugfixes.topic-type checkingRelated to type checking
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

2.10: Type checking error onmodel_fields andmodel_computed_fields with mypy
2 participants
@sydney-runkle@Viicos

[8]ページ先頭

©2009-2025 Movatter.jp