pydantic
pydantic copied to clipboard
Allow computed fields (and methods) to be provided with `create_model()`
Initial Checks
- [x] I have searched Google & GitHub for similar requests and couldn't find anything
- [x] I have read and followed the docs and still think this feature is missing
Description
As per https://github.com/pydantic/pydantic/issues/11708 and https://github.com/pydantic/pydantic/discussions/7760.
Affected Components
- [ ] Compatibility between releases
- [ ] Data validation/parsing
- [ ] Data serialization -
.model_dump()and.model_dump_json() - [ ] JSON Schema
- [ ] Dataclasses
- [ ] Model Config
- [ ] Field Types - adding or changing a particular data type
- [ ] Function validation decorator
- [ ] Generic Models
- [ ] Other Model behaviour -
model_construct(), pickling, private attributes, ORM mode - [ ] Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.
@Viicos
Hi, I did some additional investigation.
After the change pydantic/pydantic#11032, which caused the issue, it turns out that PydanticDescriptorProxy objects are now stored in __annotations__.
As a result, it's no longer possible to iterate over them during the DecoratorInfos.build call.
Hope this helps a bit ;)
I just ran into this. Did anyone come up with a hotfix that worked for them?
A possible fix - make the annotation declaration optional:
https://github.com/pydantic/pydantic/blob/2e7cddb6a7600311c4a29763efd55596a826edde/pydantic/main.py#L1742-L1746
annotations[f_name] = f_def[0]
fields[f_name] = f_def[1]
else:
annotations[f_name] = f_def
if f_def[0]:
annotations[f_name] = f_def[0]
fields[f_name] = f_def[1]
else:
annotations[f_name] = f_def
I've copied create_model to include this.
https://github.com/commonism/aiopenapi3/blob/167c51068c8a59126d03ab3193d72d610d3dcbd9/aiopenapi3/pydanticv2.py#L38-L116
It defines fields without annotation instead of using None as annotation. I use it for properties.
As a workaround that can be used with the current create_model() function, anything can be passed to __validators__ (it is used directly to update the class namespace).
I think we'll add a new parameter (something like __namespace_updates__ or similar), and we may deprecate __validators__ in favor of this one.
As it's too late for 2.12, any chance for 2.13?