-
Notifications
You must be signed in to change notification settings - Fork 8
Add dataclass and pydantic support with simplified implementation #33
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
1aacb80
Add dataclass and pydantic support
LockedThread 96c7ac5
Remove dataclass and pydantic support from defaults
LockedThread 1cdf01c
remove unnecessary comments
LockedThread dbe484e
Merge branch 'main' into feat/add-pydantic-dataclasses-support
LockedThread afdcd06
Merge branch 'main' into feat/add-pydantic-dataclasses-support
LockedThread 6132759
Run rustfmt
LockedThread 6e417a2
Merge branch 'main' into pr/LockedThread/23
termoshtt 5c303f4
Fix deprecation warnings and dead code in pydantic/dataclass support
termoshtt 41b4c6b
Merge branch 'main' into pr/LockedThread/23
termoshtt 03cbff3
Address GitHub Copilot review feedback
termoshtt 38f1da8
Remove dataclass feature gating (Python stdlib support)
termoshtt c9b8f4b
Reorganize test suite with comprehensive documentation
termoshtt 60e70f8
Further split Python type tests into focused files
termoshtt 35e13cc
Drop pydantic_support feature flag and always enable pydantic support
termoshtt 883c467
More
termoshtt 2061fdb
Fix PyO3 version to 0.26.0 on test
termoshtt 6b88be5
Use PyO3 0.27.0 or later
termoshtt 6af04a5
Fix deprecated
termoshtt 73a5eff
Install pydantic in test
termoshtt 4f3f466
Add test matrix for pydantic and abi3 combinations
termoshtt 07436d9
Add name
termoshtt 873eeed
Re-implement dataclass support in a separate module
termoshtt c05a8ee
Refactor pydantic support to match dataclass pattern
termoshtt b1806c2
Do not cast to PyFunction for supporting abi3 case
termoshtt 539a4ce
Skip pydantic test when pydantic is not installed
termoshtt c3c1ee9
Do not use expect
termoshtt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| use pyo3::{types::*, Bound, PyResult, Python}; | ||
|
|
||
| /// Check if the given object is an instance of a dataclass by `dataclasses.is_dataclass`, | ||
| /// and convert it to a PyDict using `dataclasses.asdict`. | ||
| pub fn dataclass_as_dict<'py>( | ||
| py: Python<'py>, | ||
| obj: &Bound<'py, PyAny>, | ||
| ) -> PyResult<Option<Bound<'py, PyDict>>> { | ||
| let module = PyModule::import(py, "dataclasses")?; | ||
| let is_dataclass_fn = module.getattr("is_dataclass")?; | ||
|
|
||
| if is_dataclass_fn.call1((obj,))?.extract::<bool>()? { | ||
| let asdict_fn = module.getattr("asdict")?; | ||
| let dict_obj = asdict_fn.call1((obj,))?; | ||
| let dict = dict_obj.cast_into::<PyDict>()?; | ||
| Ok(Some(dict)) | ||
| } else { | ||
| Ok(None) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,8 +4,10 @@ | |
| //! to Python objects. | ||
| //! | ||
|
|
||
| mod dataclass; | ||
| mod de; | ||
| mod error; | ||
| mod pydantic; | ||
| mod pylit; | ||
| mod ser; | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| use pyo3::{types::*, Bound, PyResult, Python}; | ||
|
|
||
| /// Check if the given object is an instance of pydantic BaseModel, | ||
| /// and convert it to a PyDict using `model_dump()`. | ||
| /// | ||
| /// If pydantic is not installed, this function returns Ok(None). | ||
| pub fn pydantic_model_as_dict<'py>( | ||
| py: Python<'py>, | ||
| obj: &Bound<'py, PyAny>, | ||
| ) -> PyResult<Option<Bound<'py, PyDict>>> { | ||
| // Try to import pydantic module | ||
| let module = match PyModule::import(py, "pydantic") { | ||
| Ok(m) => m, | ||
| Err(_) => { | ||
| // If pydantic import fails for any reason, return None | ||
| log::debug!("pydantic module not found; skipping pydantic model check"); | ||
| return Ok(None); | ||
| } | ||
| }; | ||
|
|
||
| let base_model = module.getattr("BaseModel")?.cast_into::<PyType>()?; | ||
|
|
||
| if obj.is_instance(&base_model)? { | ||
| let model_dump_fn = obj.getattr("model_dump")?; | ||
| let dict_obj = model_dump_fn.call0()?; | ||
| let dict = dict_obj.cast_into::<PyDict>()?; | ||
| Ok(Some(dict)) | ||
| } else { | ||
| Ok(None) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| //! Custom Python Class Tests (Python → Rust) | ||
| //! | ||
| //! This test suite verifies deserialization support for custom Python classes | ||
| //! that use the `__dict__` attribute to store instance data. | ||
| //! | ||
| //! These are user-defined Python classes created with the `class` keyword and | ||
| //! `__init__` method, which is the most basic and common way to define classes | ||
| //! in Python. | ||
| //! | ||
| //! Each test: | ||
| //! 1. Defines a Python class with `__init__` method | ||
| //! 2. Creates an instance of that class | ||
| //! 3. Deserializes the Python object to a Rust struct via `from_pyobject` | ||
| //! 4. Verifies correctness by comparing with a Rust-originated value | ||
| //! | ||
| //! This ensures that basic Python objects can be seamlessly deserialized into | ||
| //! Rust structures, enabling interoperability with user-defined Python types. | ||
|
|
||
| use pyo3::{ffi::c_str, prelude::*}; | ||
| use serde::{Deserialize, Serialize}; | ||
| use serde_pyobject::{from_pyobject, to_pyobject}; | ||
|
|
||
| #[test] | ||
| fn check_python_object() { | ||
| #[derive(Debug, PartialEq, Serialize, Deserialize)] | ||
| struct MyClass { | ||
| name: String, | ||
| age: i32, | ||
| } | ||
|
|
||
| Python::attach(|py| { | ||
| // Create an instance of Python object | ||
| py.run( | ||
| c_str!( | ||
| r#" | ||
| class MyClass: | ||
| def __init__(self, name: str, age: int): | ||
| self.name = name | ||
| self.age = age | ||
| "# | ||
| ), | ||
| None, | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
| // Create an instance of MyClass | ||
| let my_python_class = py | ||
| .eval( | ||
| c_str!( | ||
| r#" | ||
| MyClass("John", 30) | ||
| "# | ||
| ), | ||
| None, | ||
| None, | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| let my_rust_class = MyClass { | ||
| name: "John".to_string(), | ||
| age: 30, | ||
| }; | ||
| let any: Bound<'_, PyAny> = to_pyobject(py, &my_rust_class).unwrap(); | ||
| let rust_version: MyClass = from_pyobject(my_python_class).unwrap(); | ||
| let python_version: MyClass = from_pyobject(any).unwrap(); | ||
| assert_eq!(rust_version, python_version); | ||
| }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.