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

Add option to exclude a field using a callable#1535

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

Open
andresliszt wants to merge6 commits intopydantic:main
base:main
Choose a base branch
Loading
fromandresliszt:support/exclude-if-at-field-level

Conversation

andresliszt
Copy link

@andreslisztandresliszt commentedNov 8, 2024
edited
Loading

Change Summary

This PR aims to add support for excluding field from serialization based on condition. As@davidhewitt suggested I added a newexclude_if argument at field level, which is callable that checks if the field value meets a condition. However, in this pydanticissue David suggested to useskip_serializing_if from Rust's serde, I could't find a way to use it due that serialization is being doing a loop for each field usingserialize_map.

Related issue number

pydantic/pydantic#10728

Checklist

  • Unit tests for the changes exist
  • Documentation reflects the changes where applicable
  • Pydantic tests pass with thispydantic-core (except for expected changes)
  • My PR is ready to review,please add a comment including the phrase "please review" to assign reviewers

Selected Reviewer:@sydney-runkle

sh-at-cs reacted with thumbs up emoji
@codecovCodecov
Copy link

codecovbot commentedNov 8, 2024
edited
Loading

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report?Let us know!

@andresliszt
Copy link
Author

please review

pydantic-hooky[bot] reacted with thumbs up emoji

@codspeed-hqCodSpeed HQ
Copy link

codspeed-hqbot commentedNov 8, 2024
edited
Loading

CodSpeed Performance Report

Merging#1535 willnot alter performance

Comparingandresliszt:support/exclude-if-at-field-level (a836948) withmain (83ff1cf)

Summary

✅ 155 untouched benchmarks

serializer: &CombinedSerializer,
) -> PyResult<bool> {
let py = value.py();

Copy link
Author

Choose a reason for hiding this comment

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

think this should be called only if any condition is met, right? inside theif

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should probably handle this outside of theexclude_default function as to decouple them for readability. We don't coupleexclude_default withexclude_none orexclude_unset, so I think we should retain separation here as well!

andresliszt reacted with thumbs up emoji
@sydney-runkle
Copy link
Contributor

Super exciting! Will give this a thorough review soon. Working on getting v2.10 out, and this will be included in v2.11 :)

andresliszt reacted with hooray emoji

Copy link
Contributor

@sydney-runklesydney-runkle left a comment

Choose a reason for hiding this comment

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

Would love to see an implementation on thepydantic side as well - you can point to this branch.

Looks like a great start. I'm impressed with how simple this is going to be!

serializer: &CombinedSerializer,
) -> PyResult<bool> {
let py = value.py();

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should probably handle this outside of theexclude_default function as to decouple them for readability. We don't coupleexclude_default withexclude_none orexclude_unset, so I think we should retain separation here as well!

andresliszt reacted with thumbs up emoji
@sydney-runkle
Copy link
Contributor

I would anticipate that folks might want to set this at themodel_dump level as well, and I think we should probably support that too, given that's where the otherexclude_X specs live.

yorickvP and daragok reacted with thumbs up emojidaragok reacted with hooray emojidaragok reacted with heart emoji

@andresliszt
Copy link
Author

Would love to see an implementation on thepydantic side as well - you can point to this branch.

Looks like a great start. I'm impressed with how simple this is going to be!

Hello@sydney-runkle ! How do you do the implementation inpydantic when you need apydantic-core feature? First create a release ofpydantic-core and then use it inpydantic? In this case are you requesting to create a PR inpydantic pointing to this branch to see what it looks like, right?

@andresliszt
Copy link
Author

I would anticipate that folks might want to set this at themodel_dump level as well, and I think we should probably support that too, given that's where the otherexclude_X specs live.

I'm curious how the callable should work in themodel_dump, are you thinking in a callable with one argumentCallable[[Any], bool] to be applied in all fields, for example:

classModel(BaseModel):foo:strbar:list[str]foobaz:int>>>Model(foo="",bar= [],foobaz=1).model_dump(exclude_if=lambdafield:notfield){"foobaz":1}

@sydney-runkle
Copy link
Contributor

? In this case are you requesting to create a PR in pydantic pointing to this branch to see what it looks like, right?

Yes, exactly this! Once we merge, we'll include in a minorpydantic-core release, then we can bump thepydantic-core version officially on yourpydantic PR and merge that one.

It's just helpful to see the implementation on both sides before we merge thepydantic-core one.

@sydney-runkle
Copy link
Contributor

I'm curious how the callable should work in the model_dump, are you thinking in a callable with one argument Callable[[Any], bool] to be applied in all fields

Yes, exactly this. That being said, I chatted with the team, and we decided that introducing this at the field level first makes sense, and we can follow with other config / runtime specs later.

daragok reacted with heart emojiandresliszt and daragok reacted with rocket emoji

@andreslisztandreslisztforce-pushed thesupport/exclude-if-at-field-level branch fromd7d7d0e tob225197CompareNovember 24, 2024 14:52
@andresliszt
Copy link
Author

Alright,@sydney-runkle I created a PR pointing to this branch!

sydney-runkle reacted with heart emoji

@Kevin-Mc-Callister
Copy link

Any news on this?

@joshorr
Copy link

joshorr commentedMar 31, 2025
edited
Loading

Super exciting! Will give this a thorough review soon. Working on getting v2.10 out, and this will be included in v2.11 :)

@sydney-runkle It sounds like this feature did not get out in v2.11? Any news on when it might come out?

lokhman, thibaut-lo, gboeer, annesylvie-runna, daragok, selectorseb, and Lemminkyinen reacted with thumbs up emoji

@@ -2817,7 +2817,8 @@ class TypedDictField(TypedDict, total=False):
validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
serialization_alias: str
serialization_exclude: bool # default: False
metadata: Dict[str, Any]
exclude_if: Callable[[Any], bool] # default None
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callable[[Any],bool]# default None
serialization_exclude_if:Callable[[Any],bool]# default None

@@ -2827,7 +2828,8 @@ def typed_dict_field(
validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
serialization_alias: str | None = None,
serialization_exclude: bool | None = None,
metadata: Dict[str, Any] | None = None,
exclude_if: Callable[[Any], bool] | None = None,
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callable[[Any],bool]|None=None,
serialization_exclude_if:Callable[[Any],bool]|None=None,

@@ -2844,6 +2846,7 @@ def typed_dict_field(
validation_alias: The alias(es) to use to find the field in the validation data
serialization_alias: The alias to use as a key when serializing
serialization_exclude: Whether to exclude the field when serializing
exclude_if: Callable that determines whether to exclude a field during serialization based on its value.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callablethatdetermineswhethertoexcludeafieldduringserializationbasedonitsvalue.
serialization_exclude_if:Acallablethatdetermineswhethertoexcludethefieldwhenserializingbasedonitsvalue.

@@ -2853,6 +2856,7 @@ def typed_dict_field(
validation_alias=validation_alias,
serialization_alias=serialization_alias,
serialization_exclude=serialization_exclude,
exclude_if=exclude_if,
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if=exclude_if,
serialization_exclude_if=serialization_exclude_if,

@@ -2943,6 +2947,7 @@ class ModelField(TypedDict, total=False):
validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
serialization_alias: str
serialization_exclude: bool # default: False
exclude_if: Callable[[Any], bool] # default: None
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callable[[Any],bool]# default: None
serialization_exclude_if:Callable[[Any],bool]# default: None

@@ -3171,7 +3179,8 @@ class DataclassField(TypedDict, total=False):
validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]]
serialization_alias: str
serialization_exclude: bool # default: False
metadata: Dict[str, Any]
exclude_if: Callable[[Any], bool] # default: None
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callable[[Any],bool]# default: None
serialization_exclude_if:Callable[[Any],bool]# default: None

@@ -3184,7 +3193,8 @@ def dataclass_field(
validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
serialization_alias: str | None = None,
serialization_exclude: bool | None = None,
metadata: Dict[str, Any] | None = None,
exclude_if: Callable[[Any], bool] | None = None,
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callable[[Any],bool]|None=None,
serialization_exclude_if:Callable[[Any],bool]|None=None,

@@ -3210,6 +3220,7 @@ def dataclass_field(
validation_alias: The alias(es) to use to find the field in the validation data
serialization_alias: The alias to use as a key when serializing
serialization_exclude: Whether to exclude the field when serializing
exclude_if: Callable that determines whether to exclude a field during serialization based on its value.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if:Callablethatdetermineswhethertoexcludeafieldduringserializationbasedonitsvalue.
serialization_exclude_if:Acallablethatdetermineswhethertoexcludethefieldwhenserializingbasedonitsvalue.

@@ -3223,6 +3234,7 @@ def dataclass_field(
validation_alias=validation_alias,
serialization_alias=serialization_alias,
serialization_exclude=serialization_exclude,
exclude_if=exclude_if,
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
exclude_if=exclude_if,
serialization_exclude_if=serialization_exclude_if,

@@ -80,6 +95,7 @@ fn exclude_default(value: &Bound<'_, PyAny>, extra: &Extra, serializer: &Combine
}
}
}
// If neither condition is met, do not exclude the field
Copy link
Member

Choose a reason for hiding this comment

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

Lets avoid diff noise:

Suggested change
// If neither condition is met, do not exclude the field

@ViicosViicos changed the titleSupport exclude_if callable at field levelAdd option to exclude a field using a callable levelJul 11, 2025
@ViicosViicos changed the titleAdd option to exclude a field using a callable levelAdd option to exclude a field using a callableJul 11, 2025
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@sydney-runklesydney-runklesydney-runkle left review comments

@ViicosViicosViicos requested changes

Requested changes must be addressed to merge this pull request.

Assignees

@sydney-runklesydney-runkle

Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

5 participants
@andresliszt@sydney-runkle@Kevin-Mc-Callister@joshorr@Viicos

[8]ページ先頭

©2009-2025 Movatter.jp