* moving docs to mkdocs * transfering readme to md and more * fixing build * splitting usage.md * improving schema.md and index.md * fix make_history.rst * models intro * working on data conversation and required fields * more fixes to models.md * list all standard types supported * list of pydantic types * tweaks * update links in code * Apply suggestions from code review incorporate @dmontagu's suggestions. Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com> * Apply suggestions from code review more missed suggestions. Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com> * Apply suggestions from code review more corrects. * cleanup * Field order warning * fix and regenerate benchmarks * format examples better, cleanup * improve schema mapping table * correct highlighting file types in schema.md * add redirects in javascript * add logo
2.3 KiB
!!! note
Both postponed annotations via the future import and ForwardRef require python 3.7+.
Postponed annotations (as described in PEP563) "just work".
{!./examples/postponed_annotations.py!}
(This script is complete, it should run "as is")
Internally pydantic will call a method similar to typing.get_type_hints to resolve annotations.
In cases where the referenced type is not yet defined, ForwardRef can be used (although referencing the
type directly or by its string is a simpler solution in the case of
self-referencing models).
You may need to call Model.update_forward_refs() after creating the model,
this is because in the example below Foo doesn't exist before it has been created (obviously) so ForwardRef
can't initially be resolved. You have to wait until after Foo is created, then call update_forward_refs
to properly set types before the model can be used.
{!./examples/forward_ref.py!}
(This script is complete, it should run "as is")
!!! warning
To resolve strings (type names) into annotations (types) pydantic needs a dict to lookup,
for this it uses module.__dict__ just as get_type_hints does. That means pydantic does not play well
with types not defined in the global scope of a module.
For example, this works fine:
{!./examples/postponed_works.py!}
While this will break:
{!./examples/postponed_broken.py!}
Resolving this is beyond the call for pydantic: either remove the future import or declare the types globally.
Self-referencing Models
Data structures with self-referencing models are also supported, provided the function
update_forward_refs() is called once the model is created (you will be reminded
with a friendly error message if you don't).
Within the model, you can refer to the not-yet-constructed model by a string :
{!./examples/self_referencing_string.py!}
(This script is complete, it should run "as is")
Since python 3.7, You can also refer it by its type, provided you import annotations (see
above for support depending on Python
and pydantic versions).
{!./examples/self_referencing_annotations.py!}
(This script is complete, it should run "as is")