Skip to content

Allow enums and structs to be handled by pydantic - #428

Merged
NeejWeej merged 9 commits into
mainfrom
nk/pydantic_compat_struct
Jan 24, 2025
Merged

NeejWeej merged 9 commits into
mainfrom
nk/pydantic_compat_struct

Conversation

@NeejWeej

Copy link
Copy Markdown
Contributor

No description provided.

Nijat Khanbabayev added 3 commits January 16, 2025 00:25
Signed-off-by: Nijat Khanbabayev <[email protected]>
Signed-off-by: Nijat Khanbabayev <[email protected]>
Signed-off-by: Nijat Khanbabayev <[email protected]>
ptomecek
ptomecek approved these changes Jan 16, 2025 •
Comment thread csp/impl/enum.py Resolved
Comment thread csp/tests/impl/test_struct.py Resolved
@ptomecek
ptomecek self-requested a review January 16, 2025 22:31

@ptomecek ptomecek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Some comments left in the review about testing, might need some small modifications to get this to work. Overall though, I like the approach and also think this adds very powerful functionality to csp around serialization/integration with other tools (like FastAPI).

@ptomecek

Copy link
Copy Markdown
Collaborator

Once we merge this, we should create an issue for adding documentation about this functionality to the wiki page about pydantic compatibility of csp structs.

@NeejWeej
NeejWeej requested a review from ptomecek January 17, 2025 15:13

@ptomecek ptomecek left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I noticed that the unit test is often using result.to_json to generate the json from the result, which does not go through the pydantic logic (rather it uses the native csp functionality). To go through the pydantic serialization logic, one should call TypeAdapter(cls).dump_json(), which will pick up any serializers in the annotations (whereas to_json will not).

I think we should be a bit more explicit in the tests. When testing pydantic round-trip of serialization/deserialization, use the TypeAdapter, and then have a separate test which checks that for basic types (and no custom serializers) that TypeAdapter.dump_json and Struct.to_json return the same thing.

@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch 2 times, most recently from 69fb38b to 5cf0259 Compare January 19, 2025 23:40
@NeejWeej

NeejWeej commented Jan 20, 2025 •

Copy link
Copy Markdown
Contributor Author

I noticed that the unit test is often using result.to_json to generate the json from the result, which does not go through the pydantic logic (rather it uses the native csp functionality). To go through the pydantic serialization logic, one should call TypeAdapter(cls).dump_json(), which will pick up any serializers in the annotations (whereas to_json will not).

I think we should be a bit more explicit in the tests. When testing pydantic round-trip of serialization/deserialization, use the TypeAdapter, and then have a separate test which checks that for basic types (and no custom serializers) that TypeAdapter.dump_json and Struct.to_json return the same thing.

Added these tests, and actually they found a bug.

Separately, Pydantic and csp give different results for datetime serializations to string. This can be bypassed with a custom serializer (which is demonstrated with this test here: https://github.com/Point72/csp/pull/428/files#diff-16e10f816ba9638999d038fb8bd076b4021e901b60e548b1bc392b6191026687R3649
)

@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch from 5cf0259 to e5dcc10 Compare January 20, 2025 20:17
@NeejWeej

Copy link
Copy Markdown
Contributor Author

Notably, the csp behavior with csp Enums is to serialize them to a string when calling to_dict

import csp

class MyEnum(csp.Enum):
    OPTION1 = csp.Enum.auto()
    OPTION2 = csp.Enum.auto()

class DummyS(csp.Struct):
    e: MyEnum = MyEnum.OPTION1

val = DummyS()
print(f'{val.to_dict(), val.e =  }')

We intentionally let the pydantic route maintain the Enum class when converting to a dict (this is covered in the tests)

@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch from e5dcc10 to 61dbb86 Compare January 20, 2025 20:21
@NeejWeej
NeejWeej requested a review from ptomecek January 20, 2025 21:45
@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch 2 times, most recently from 46451e4 to 71844f5 Compare January 20, 2025 22:11
@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch from 71844f5 to c1acca8 Compare January 20, 2025 22:41
@ptomecek

Copy link
Copy Markdown
Collaborator

Notably, the csp behavior with csp Enums is to serialize them to a string when calling to_dict

import csp

class MyEnum(csp.Enum):
    OPTION1 = csp.Enum.auto()
    OPTION2 = csp.Enum.auto()

class DummyS(csp.Struct):
    e: MyEnum = MyEnum.OPTION1

val = DummyS()
print(f'{val.to_dict(), val.e =  }')

We intentionally let the pydantic route maintain the Enum class when converting to a dict (this is covered in the tests)

I think this makes sense, as this is what pydantic would do for regular python enums and string enums (unless converting to json)

ptomecek
ptomecek previously approved these changes Jan 21, 2025
@NeejWeej

NeejWeej commented Jan 23, 2025 •

Copy link
Copy Markdown
Contributor Author

As discussed, since csp treats underscore attributes as first class, but pydantic doesnt, we agreed on this behavior:

  • Underscore attributes are ignored by pydantic, but pass-through to the underlying csp struct. So no type checks or validation, but they can still populate the csp Struct. Under the hood, this is implemented by specifying extra attributes as "allow". The underlying csp struct will raise an error if the attribute doesn't actually exist.
  • Since we ignore underscore attributes with pydantic, dumping to json or python via the pydantic route (from a BaseModel or with a TypeAdapter) will exclude the underscore attributes on the csp struct

@NeejWeej
NeejWeej force-pushed the nk/pydantic_compat_struct branch from b756673 to fd203b1 Compare January 24, 2025 05:22
@NeejWeej

Copy link
Copy Markdown
Contributor Author

For classes without a pydantic schema, we perform one level of validation, then, we use an 'any_schema' to err on the side of caution to not erroneously throw validation errors. We pass the attribute onto csp to allow it to decide.

@ptomecek ptomecek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for all the additional testing, which certainly brought out a number of edge cases we didn't originally think of. With all the additional test cases you've added and downstream testing, I am comfortable with the application of these changes in real-world usage.

@robambalu

Copy link
Copy Markdown
Collaborator

Notably, the csp behavior with csp Enums is to serialize them to a string when calling to_dict

import csp

class MyEnum(csp.Enum):
    OPTION1 = csp.Enum.auto()
    OPTION2 = csp.Enum.auto()

class DummyS(csp.Struct):
    e: MyEnum = MyEnum.OPTION1

val = DummyS()
print(f'{val.to_dict(), val.e =  }')

We intentionally let the pydantic route maintain the Enum class when converting to a dict (this is covered in the tests)

I think this makes sense, as this is what pydantic would do for regular python enums and string enums (unless converting to json)

FYI the reason we serialize the string is so that the encoding is stable across updates to the enum

@NeejWeej
NeejWeej merged commit daf07d4 into main Jan 24, 2025
@NeejWeej
NeejWeej deleted the nk/pydantic_compat_struct branch January 24, 2025 21:22
@timkpaine timkpaine added the type: enhancement Issues and PRs related to improvements to existing features label Feb 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: enhancement Issues and PRs related to improvements to existing features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants