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

RefactorFieldInfo creation implementation#11898

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
Viicos merged 12 commits intomainfromfieldinfo-cleanup
Jun 14, 2025
Merged

Conversation

Viicos
Copy link
Member

@ViicosViicos commentedMay 21, 2025
edited
Loading

Change Summary

(best reviewed commit per commit).

Fixes#11870,fixes#11876,fixes#11978.

Fixes#11122 (the three bugs described in the issue).

Issue#10507isn't fixed with this, but at least now properly documented as a workaround in the implementation.

Most of the context of this PR is described in#11122.

The main thing being done here is the added_construct() classmethod, that centralizes most of the merging logic and avoids repetition (which actually wasn't mirrored in every code path, that's why many inconsistencies existed depending on whether you assigned aField() to an attribute). We avoid copyingFieldInfo instances everywhere, and doing buggy metadata handling.

As a result, themerge_field_infos() method is unused (you can compare both this method and_construct() to see what changed — the latter is much simpler). We need to deprecate it as third-party projects rely on it (unfortunately..). I propose marking it as deprecatedonly for type checkers for now, and have a runtime deprecation emitted in V3?

openapi-python-client third party failure is unrelated, their CI is currently failing.

Required to fix a type checking issue
The existing implementation did not warn when a callablewas used first, then a dict. Also use a plain `UserWarning`as `PydanticJsonSchemaWarning` is meant to be used*during* JSON Schema generation.
Both were actually inconsistent, in particular when using the`warnings.deprecated` class as metadata, we would only setthe message string `FieldInfo.deprecated`.
We don't do any mutations of the assigned `Field()` anymore.
@ViicosViicos added relnotes-fixUsed for bugfixes. relnotes-changeUsed for changes to existing functionality which don't have a better categorization. third-party-testsAdd this label on a PR to trigger 3rd party tests labelsMay 21, 2025
)
default = assigned_value.default.__get__(None, cls)
assigned_value.default = default
assigned_value._attributes_set['default'] = default
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Next step would be to get rid of the_attributes_set logic when merging instances, which is error prone as you need to update it whenever you do a manual assignment on aFieldInfo instance.

@@ -213,7 +213,7 @@ def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:

See the signature of `pydantic.fields.Field` for more details about the expected arguments.
"""
self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset}
self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset and k not in self.metadata_lookup}
Copy link
MemberAuthor

@ViicosViicosMay 21, 2025
edited
Loading

Choose a reason for hiding this comment

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

This is kind of important, although it also works without the change:

When we merge field infos, we don't want to reinclude kwargs that are transformed to metadata elements (gt ->annotated_types.Gt, etc). This will result in unnecessary metadata classes to be created (at the end of theFieldInfo.__init__() logic).

@codspeed-hqCodSpeed HQ
Copy link

codspeed-hqbot commentedMay 21, 2025
edited
Loading

CodSpeed Performance Report

Merging#11898 willdegrade performances by 13.42%

Comparingfieldinfo-cleanup (3ce5218) withmain (11a24ef)

Summary

❌ 1 regressions
✅ 45 untouched benchmarks

⚠️Please fix the performance issues oracknowledge them on CodSpeed.

Benchmarks breakdown

BenchmarkBASEHEADChange
test_failed_rebuild218 µs251.7 µs-13.42%

@github-actionsGitHub Actions
Copy link
Contributor

github-actionsbot commentedMay 21, 2025
edited
Loading

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  pydantic
  fields.py
  pydantic/_internal
  _fields.py
Project Total 

This report was generated bypython-coverage-comment-action

@ViicosViicos added the needs-blogpost-entryThis PR needs to be documented in the release notes blog post labelMay 22, 2025
@cloudflare-workers-and-pagesCloudflare Workers and Pages
Copy link

cloudflare-workers-and-pagesbot commentedMay 22, 2025
edited
Loading

Deploying pydantic-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit:3ce5218
Status: ✅  Deploy successful!
Preview URL:https://96843f8e.pydantic-docs.pages.dev
Branch Preview URL:https://fieldinfo-cleanup.pydantic-docs.pages.dev

View logs

Comment on lines +741 to +762
def _copy(self) -> Self:
"""Return a copy of the `FieldInfo` instance."""
# Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
# by some third-party libraries with extra attributes defined (and as `FieldInfo`
# is slotted, we can't make a copy of the `__dict__`).
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Alternatively, we can drop slots onFieldInfo, and do the following:

def__copy__(self)->Self:copied=type(self)()copied.__dict__=self.__dict__forattr_namein ('metadata','_attributes_set','_qualifiers'):# Apply "deep-copy" behavior on collections attributes:value=getattr(self,attr_name).copy()setattr(copied,attr_name,value)returncopied

@@ -505,28 +505,6 @@ class AnnotatedFieldModel(BaseModel):
}
]

# Ensure that the inner annotation does not override the outer, even for metadata:
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Due to one of the bugs being fixed in this PR (related to the usage of forward references), the constraint inAnnotated was dropped. Now the test is failing because the unexpected order (described in#10507) applies.

Comment on lines +410 to +418
# HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
# instance's type to be preserved when constructing new models with its subclasses as assignments.
# This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo:
field_info = default._copy()
field_info._attributes_set.update(attr_overrides)
for k, v in attr_overrides.items():
setattr(field_info, k, v)
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Unfortunate stuff introduced since#6862..

@Viicos
Copy link
MemberAuthor

cc@zmievsa, I've tried looking into the Cadwyn issues but got too scared by the code base.

@zmievsa
Copy link
Contributor

zmievsa commentedMay 23, 2025
edited
Loading

Apologies for not fixing it yesterday. I'll fix it in a second

Update: oh, I see that it's unrelated to my recent problems with Cadwyn CI. Well, I'll fix it now anyways :)

@Viicos
Copy link
MemberAuthor

No rush, the third-party CI is not blocking and this is only going to be included in 2.12 anyway.

@zmievsa
Copy link
Contributor

zmievsa commentedMay 24, 2025
edited
Loading

@Viicos WDYT about this approach for extracting metadata? Is this the correct interface to use? (it works according to my tests but I am worried that I'm using the wrong abstraction from pydantic for extracting it
zmievsa/cadwyn#281

Copy link
Contributor

@DouweMDouweM left a comment

Choose a reason for hiding this comment

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

@Viicos Great work Victorien, the separate commits and your comments were very helpful! Just 2 questions aboutprepend_metadata.

@pydantic-hookypydantic-hookybot added the awaiting author revisionawaiting changes from the PR author labelJun 12, 2025
@ViicosViicos requested a review fromDouweMJune 13, 2025 09:12
@ViicosViicos merged commit565cea9 intomainJun 14, 2025
88 of 90 checks passed
@ViicosViicos deleted the fieldinfo-cleanup branchJune 14, 2025 08:45
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@DouweMDouweMDouweM approved these changes

Assignees

@ViicosViicos

Labels
awaiting author revisionawaiting changes from the PR authorneeds-blogpost-entryThis PR needs to be documented in the release notes blog postrelnotes-changeUsed for changes to existing functionality which don't have a better categorization.relnotes-fixUsed for bugfixes.third-party-testsAdd this label on a PR to trigger 3rd party tests
Projects
None yet
Milestone
No milestone
3 participants
@Viicos@zmievsa@DouweM

[8]ページ先頭

©2009-2025 Movatter.jp