feature: add instance level ref cache #63

Merged
HideyoshiNakazone merged 12 commits from feature/add-instance-level-ref-cache into main 2025-11-25 00:07:55 +00:00
2 changed files with 20 additions and 7 deletions
Showing only changes of commit a3cbd5bc3d - Show all commits

View File

@@ -64,19 +64,17 @@ class ObjectTypeParser(GenericTypeParser):
) )
if (model := ref_cache.get(name)) is not None and isinstance(model, type): if (model := ref_cache.get(name)) is not None and isinstance(model, type):
warnings.warn(
f"Type '{name}' is already in the ref_cache and therefore cached value will be used."
" This may indicate a namming collision in the schema or just a normal optimization,"
" if this behavior is desired pass a clean ref_cache or use the param `without_cache`"
)
return model return model
model_config = ConfigDict(validate_assignment=True) model_config = ConfigDict(validate_assignment=True)
fields = cls._parse_properties(name, properties, required_keys, **kwargs) fields = cls._parse_properties(name, properties, required_keys, **kwargs)
model = create_model(name, __config__=model_config, **fields) # type: ignore model = create_model(name, __config__=model_config, **fields) # type: ignore
if name in ref_cache and isinstance(ref_cache[name], type):
warnings.warn(
f"Type '{name}' is already in the ref_cache and will be overwritten."
" This may indicate a circular reference in the schema or a collision in the schema.",
UserWarning,
)
ref_cache[name] = model ref_cache[name] = model
return model return model

View File

@@ -92,3 +92,18 @@ class TestObjectTypeParser(TestCase):
# Chekc default factory new object id # Chekc default factory new object id
new_obj = type_validator["default_factory"]() new_obj = type_validator["default_factory"]()
self.assertNotEqual(id(default_obj), id(new_obj)) self.assertNotEqual(id(default_obj), id(new_obj))
def test_object_type_parser_warns_if_object_override_in_cache(self):
ref_cache = {}
parser = ObjectTypeParser()
properties = {"type": "object", "properties": {}}
with self.assertWarns(UserWarning):
_, type_validator = parser.from_properties_impl(
"placeholder", properties, ref_cache=ref_cache
)
_, type_validator = parser.from_properties_impl(
"placeholder", properties, ref_cache=ref_cache
)