- 
                Notifications
    
You must be signed in to change notification settings  - Fork 312
 
          Memory usage optimization via reuse of SchemaValidator and SchemaSerializer
          #1616
        
          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 4 commits
      Commits
    
    
            Show all changes
          
          
            13 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      75bde54
              
                using prebuilt validators
              
              
                sydney-runkle 5835c59
              
                linting
              
              
                sydney-runkle e5245b5
              
                linting and inheritance fix
              
              
                sydney-runkle 980fa20
              
                serializer reuse logic as well
              
              
                sydney-runkle 8bd3ef2
              
                handling for mappingproxy rather than dict on classes
              
              
                sydney-runkle 8e754c4
              
                using more simple py approach
              
              
                sydney-runkle 57671e8
              
                edge case for generic dataclasses
              
              
                sydney-runkle a8a7c5e
              
                fix name function for validator
              
              
                sydney-runkle 78f18b3
              
                restructuring recs from david
              
              
                sydney-runkle 8a9b535
              
                Merge branch 'main' into prebuilt-variant
              
              
                sydney-runkle bbaef68
              
                confirming prebuilt usage via a test
              
              
                sydney-runkle 3267736
              
                Merge branch 'prebuilt-variant' of https://github.com/pydantic/pydant…
              
              
                sydney-runkle 99136a5
              
                refactor common extraction logic
              
              
                sydney-runkle 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
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| use std::borrow::Cow; | ||
| use std::sync::Arc; | ||
| 
     | 
||
| use pyo3::exceptions::PyValueError; | ||
| use pyo3::intern; | ||
| use pyo3::prelude::*; | ||
| use pyo3::types::{PyBool, PyDict, PyType}; | ||
| 
     | 
||
| use crate::definitions::DefinitionsBuilder; | ||
| use crate::tools::SchemaDict; | ||
| use crate::SchemaSerializer; | ||
| 
     | 
||
| use super::extra::Extra; | ||
| use super::shared::{BuildSerializer, CombinedSerializer, TypeSerializer}; | ||
| 
     | 
||
| #[derive(Debug)] | ||
| pub struct PrebuiltSerializer { | ||
| serializer: Arc<CombinedSerializer>, | ||
| } | ||
| 
     | 
||
| impl BuildSerializer for PrebuiltSerializer { | ||
| const EXPECTED_TYPE: &'static str = "prebuilt"; | ||
| 
     | 
||
| fn build( | ||
| schema: &Bound<'_, PyDict>, | ||
| _config: Option<&Bound<'_, PyDict>>, | ||
| _definitions: &mut DefinitionsBuilder<CombinedSerializer>, | ||
| ) -> PyResult<CombinedSerializer> { | ||
| let py = schema.py(); | ||
| let class: Bound<'_, PyType> = schema.get_as_req(intern!(py, "cls"))?; | ||
| 
     | 
||
| // note: we NEED to use the __dict__ here (and perform get_item calls rather than getattr) | ||
| // because we don't want to fetch prebuilt serializers from parent classes | ||
| let class_dict: Bound<'_, PyDict> = class.getattr(intern!(py, "__dict__"))?.extract()?; | ||
| 
     | 
||
| // Ensure the class has completed its Pydantic setup | ||
| let is_complete: bool = class_dict | ||
| .get_as_req::<Bound<'_, PyBool>>(intern!(py, "__pydantic_complete__")) | ||
| .is_ok_and(|b| b.extract().unwrap_or(false)); | ||
| 
     | 
||
| if !is_complete { | ||
| return Err(PyValueError::new_err("Prebuilt serializer not found.")); | ||
| } | ||
| 
     | 
||
| // Retrieve the prebuilt validator if available | ||
| let prebuilt_serializer: Bound<'_, PyAny> = class_dict.get_as_req(intern!(py, "__pydantic_serializer__"))?; | ||
| let schema_serializer: PyRef<SchemaSerializer> = prebuilt_serializer.extract()?; | ||
| let combined_serializer: Arc<CombinedSerializer> = schema_serializer.serializer.clone(); | ||
| 
     | 
||
| Ok(Self { | ||
| serializer: combined_serializer, | ||
| } | ||
| .into()) | ||
| } | ||
| } | ||
| 
     | 
||
| impl_py_gc_traverse!(PrebuiltSerializer { serializer }); | ||
| 
     | 
||
| impl TypeSerializer for PrebuiltSerializer { | ||
| fn to_python( | ||
| &self, | ||
| value: &Bound<'_, PyAny>, | ||
| include: Option<&Bound<'_, PyAny>>, | ||
| exclude: Option<&Bound<'_, PyAny>>, | ||
| extra: &Extra, | ||
| ) -> PyResult<PyObject> { | ||
| self.serializer.to_python(value, include, exclude, extra) | ||
| } | ||
| 
     | 
||
| fn json_key<'a>(&self, key: &'a Bound<'_, PyAny>, extra: &Extra) -> PyResult<Cow<'a, str>> { | ||
| self.serializer.json_key(key, extra) | ||
| } | ||
| 
     | 
||
| fn serde_serialize<S: serde::ser::Serializer>( | ||
| &self, | ||
| value: &Bound<'_, PyAny>, | ||
| serializer: S, | ||
| include: Option<&Bound<'_, PyAny>>, | ||
| exclude: Option<&Bound<'_, PyAny>>, | ||
| extra: &Extra, | ||
| ) -> Result<S::Ok, S::Error> { | ||
| self.serializer | ||
| .serde_serialize(value, serializer, include, exclude, extra) | ||
| } | ||
| 
     | 
||
| fn get_name(&self) -> &str { | ||
| self.serializer.get_name() | ||
| } | ||
| 
     | 
||
| fn retry_with_lax_check(&self) -> bool { | ||
| self.serializer.retry_with_lax_check() | ||
| } | ||
| } | 
  
    
      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,74 @@ | ||
| use std::sync::Arc; | ||
| 
     | 
||
| use pyo3::exceptions::PyValueError; | ||
| use pyo3::intern; | ||
| use pyo3::prelude::*; | ||
| use pyo3::types::{PyBool, PyDict, PyType}; | ||
| 
     | 
||
| use crate::errors::ValResult; | ||
| use crate::input::Input; | ||
| use crate::tools::SchemaDict; | ||
| 
     | 
||
| use super::ValidationState; | ||
| use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, SchemaValidator, Validator}; | ||
| 
     | 
||
| #[derive(Debug)] | ||
| pub struct PrebuiltValidator { | ||
| validator: Arc<CombinedValidator>, | ||
| name: String, | ||
| } | ||
| 
     | 
||
| impl BuildValidator for PrebuiltValidator { | ||
| const EXPECTED_TYPE: &'static str = "prebuilt"; | ||
                
      
                  sydney-runkle marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| fn build( | ||
| schema: &Bound<'_, PyDict>, | ||
| _config: Option<&Bound<'_, PyDict>>, | ||
| _definitions: &mut DefinitionsBuilder<CombinedValidator>, | ||
| ) -> PyResult<CombinedValidator> { | ||
| let py = schema.py(); | ||
| let class: Bound<'_, PyType> = schema.get_as_req(intern!(py, "cls"))?; | ||
| 
     | 
||
| // note: we NEED to use the __dict__ here (and perform get_item calls rather than getattr) | ||
| // because we don't want to fetch prebuilt validators from parent classes | ||
| let class_dict: Bound<'_, PyDict> = class.getattr(intern!(py, "__dict__"))?.extract()?; | ||
| 
     | 
||
| // Ensure the class has completed its Pydantic validation setup | ||
| let is_complete: bool = class_dict | ||
| .get_as_req::<Bound<'_, PyBool>>(intern!(py, "__pydantic_complete__")) | ||
| .is_ok_and(|b| b.extract().unwrap_or(false)); | ||
| 
     | 
||
| if !is_complete { | ||
| return Err(PyValueError::new_err("Prebuilt validator not found.")); | ||
                
      
                  sydney-runkle marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| 
     | 
||
| // Retrieve the prebuilt validator if available | ||
| let prebuilt_validator: Bound<'_, PyAny> = class_dict.get_as_req(intern!(py, "__pydantic_validator__"))?; | ||
| let schema_validator: PyRef<SchemaValidator> = prebuilt_validator.extract()?; | ||
| let combined_validator: Arc<CombinedValidator> = schema_validator.validator.clone(); | ||
| let name: String = class.getattr(intern!(py, "__name__"))?.extract()?; | ||
| 
     | 
||
| Ok(Self { | ||
| validator: combined_validator, | ||
| name, | ||
| } | ||
| .into()) | ||
| } | ||
| } | ||
| 
     | 
||
| impl_py_gc_traverse!(PrebuiltValidator { validator }); | ||
| 
     | 
||
| impl Validator for PrebuiltValidator { | ||
| fn validate<'py>( | ||
| &self, | ||
| py: Python<'py>, | ||
| input: &(impl Input<'py> + ?Sized), | ||
| state: &mut ValidationState<'_, 'py>, | ||
| ) -> ValResult<PyObject> { | ||
| self.validator.validate(py, input, state) | ||
| } | ||
| 
     | 
||
| fn get_name(&self) -> &str { | ||
| &self.name | ||
                
      
                  sydney-runkle marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| } | ||
  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.