Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/INSTALLER +1 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/METADATA +1017 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/RECORD +219 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/REQUESTED +0 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/WHEEL +4 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/direct_url.json +1 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/licenses/LICENSE +21 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/__init__.py +0 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_config.py +383 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_core_metadata.py +97 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_core_utils.py +174 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_dataclasses.py +315 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_decorators.py +858 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_decorators_v1.py +174 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_discriminated_union.py +479 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_docs_extraction.py +113 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_fields.py +635 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_forward_ref.py +23 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py +0 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_generics.py +543 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_git.py +27 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_import_utils.py +20 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_internal_dataclass.py +7 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_known_annotated_metadata.py +401 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_mock_val_ser.py +228 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_model_construction.py +848 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_namespace_utils.py +293 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_repr.py +124 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_schema_gather.py +209 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py +125 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_serializers.py +53 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_signature.py +188 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_typing_extra.py +760 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_utils.py +443 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_validate_call.py +140 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_validators.py +533 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/__init__.py +0 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/class_validators.py +256 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/config.py +72 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/copy_internals.py +224 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/decorator.py +284 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/json.py +141 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/parse.py +80 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/tools.py +103 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/__init__.py +1 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/arguments_schema.py +44 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/missing_sentinel.py +5 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/pipeline.py +654 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/plugin/__init__.py +193 -0
- miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/plugin/_loader.py +58 -0
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/METADATA
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: pydantic
|
| 3 |
+
Version: 2.12.4
|
| 4 |
+
Summary: Data validation using Python type hints
|
| 5 |
+
Project-URL: Homepage, https://github.com/pydantic/pydantic
|
| 6 |
+
Project-URL: Documentation, https://docs.pydantic.dev
|
| 7 |
+
Project-URL: Funding, https://github.com/sponsors/samuelcolvin
|
| 8 |
+
Project-URL: Source, https://github.com/pydantic/pydantic
|
| 9 |
+
Project-URL: Changelog, https://docs.pydantic.dev/latest/changelog/
|
| 10 |
+
Author-email: Samuel Colvin <s@muelcolvin.com>, Eric Jolibois <em.jolibois@gmail.com>, Hasan Ramezani <hasan.r67@gmail.com>, Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Terrence Dorsey <terry@pydantic.dev>, David Montague <david@pydantic.dev>, Serge Matveenko <lig@countzero.co>, Marcelo Trylesinski <marcelotryle@gmail.com>, Sydney Runkle <sydneymarierunkle@gmail.com>, David Hewitt <mail@davidhewitt.io>, Alex Hall <alex.mojaki@gmail.com>, Victorien Plot <contact@vctrn.dev>, Douwe Maan <hi@douwe.me>
|
| 11 |
+
License-Expression: MIT
|
| 12 |
+
License-File: LICENSE
|
| 13 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 14 |
+
Classifier: Framework :: Hypothesis
|
| 15 |
+
Classifier: Framework :: Pydantic
|
| 16 |
+
Classifier: Intended Audience :: Developers
|
| 17 |
+
Classifier: Intended Audience :: Information Technology
|
| 18 |
+
Classifier: Operating System :: OS Independent
|
| 19 |
+
Classifier: Programming Language :: Python
|
| 20 |
+
Classifier: Programming Language :: Python :: 3
|
| 21 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 28 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 29 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 30 |
+
Classifier: Topic :: Internet
|
| 31 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 32 |
+
Requires-Python: >=3.9
|
| 33 |
+
Requires-Dist: annotated-types>=0.6.0
|
| 34 |
+
Requires-Dist: pydantic-core==2.41.5
|
| 35 |
+
Requires-Dist: typing-extensions>=4.14.1
|
| 36 |
+
Requires-Dist: typing-inspection>=0.4.2
|
| 37 |
+
Provides-Extra: email
|
| 38 |
+
Requires-Dist: email-validator>=2.0.0; extra == 'email'
|
| 39 |
+
Provides-Extra: timezone
|
| 40 |
+
Requires-Dist: tzdata; (python_version >= '3.9' and platform_system == 'Windows') and extra == 'timezone'
|
| 41 |
+
Description-Content-Type: text/markdown
|
| 42 |
+
|
| 43 |
+
# Pydantic Validation
|
| 44 |
+
|
| 45 |
+
[](https://github.com/pydantic/pydantic/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
|
| 46 |
+
[](https://coverage-badge.samuelcolvin.workers.dev/redirect/pydantic/pydantic)
|
| 47 |
+
[](https://pypi.python.org/pypi/pydantic)
|
| 48 |
+
[](https://anaconda.org/conda-forge/pydantic)
|
| 49 |
+
[](https://pepy.tech/project/pydantic)
|
| 50 |
+
[](https://github.com/pydantic/pydantic)
|
| 51 |
+
[](https://github.com/pydantic/pydantic/blob/main/LICENSE)
|
| 52 |
+
[](https://docs.pydantic.dev/latest/contributing/#badges)
|
| 53 |
+
[](https://docs.pydantic.dev/latest/llms.txt)
|
| 54 |
+
|
| 55 |
+
Data validation using Python type hints.
|
| 56 |
+
|
| 57 |
+
Fast and extensible, Pydantic plays nicely with your linters/IDE/brain.
|
| 58 |
+
Define how data should be in pure, canonical Python 3.9+; validate it with Pydantic.
|
| 59 |
+
|
| 60 |
+
## Pydantic Logfire :fire:
|
| 61 |
+
|
| 62 |
+
We've recently launched Pydantic Logfire to help you monitor your applications.
|
| 63 |
+
[Learn more](https://pydantic.dev/articles/logfire-announcement)
|
| 64 |
+
|
| 65 |
+
## Pydantic V1.10 vs. V2
|
| 66 |
+
|
| 67 |
+
Pydantic V2 is a ground-up rewrite that offers many new features, performance improvements, and some breaking changes compared to Pydantic V1.
|
| 68 |
+
|
| 69 |
+
If you're using Pydantic V1 you may want to look at the
|
| 70 |
+
[pydantic V1.10 Documentation](https://docs.pydantic.dev/) or,
|
| 71 |
+
[`1.10.X-fixes` git branch](https://github.com/pydantic/pydantic/tree/1.10.X-fixes). Pydantic V2 also ships with the latest version of Pydantic V1 built in so that you can incrementally upgrade your code base and projects: `from pydantic import v1 as pydantic_v1`.
|
| 72 |
+
|
| 73 |
+
## Help
|
| 74 |
+
|
| 75 |
+
See [documentation](https://docs.pydantic.dev/) for more details.
|
| 76 |
+
|
| 77 |
+
## Installation
|
| 78 |
+
|
| 79 |
+
Install using `pip install -U pydantic` or `conda install pydantic -c conda-forge`.
|
| 80 |
+
For more installation options to make Pydantic even faster,
|
| 81 |
+
see the [Install](https://docs.pydantic.dev/install/) section in the documentation.
|
| 82 |
+
|
| 83 |
+
## A Simple Example
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
from datetime import datetime
|
| 87 |
+
from typing import Optional
|
| 88 |
+
from pydantic import BaseModel
|
| 89 |
+
|
| 90 |
+
class User(BaseModel):
|
| 91 |
+
id: int
|
| 92 |
+
name: str = 'John Doe'
|
| 93 |
+
signup_ts: Optional[datetime] = None
|
| 94 |
+
friends: list[int] = []
|
| 95 |
+
|
| 96 |
+
external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']}
|
| 97 |
+
user = User(**external_data)
|
| 98 |
+
print(user)
|
| 99 |
+
#> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
|
| 100 |
+
print(user.id)
|
| 101 |
+
#> 123
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## Contributing
|
| 105 |
+
|
| 106 |
+
For guidance on setting up a development environment and how to make a
|
| 107 |
+
contribution to Pydantic, see
|
| 108 |
+
[Contributing to Pydantic](https://docs.pydantic.dev/contributing/).
|
| 109 |
+
|
| 110 |
+
## Reporting a Security Vulnerability
|
| 111 |
+
|
| 112 |
+
See our [security policy](https://github.com/pydantic/pydantic/security/policy).
|
| 113 |
+
|
| 114 |
+
## Changelog
|
| 115 |
+
|
| 116 |
+
<!-- markdownlint-disable no-bare-urls -->
|
| 117 |
+
<!-- markdownlint-disable descriptive-link-text -->
|
| 118 |
+
<!-- markdownlint-disable-next-line first-line-heading -->
|
| 119 |
+
|
| 120 |
+
## v2.12.4 (2025-11-05)
|
| 121 |
+
|
| 122 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.4)
|
| 123 |
+
|
| 124 |
+
This is the fourth 2.12 patch release, fixing more regressions, and reverting a change in the `build()` method
|
| 125 |
+
of the [`AnyUrl` and Dsn types](https://docs.pydantic.dev/latest/api/networks/).
|
| 126 |
+
|
| 127 |
+
This patch release also fixes an issue with the serialization of IP address types, when `serialize_as_any` is used. The next patch release
|
| 128 |
+
will try to address the remaining issues with *serialize as any* behavior by introducing a new *polymorphic serialization* feature, that
|
| 129 |
+
should be used in most cases in place of *serialize as any*.
|
| 130 |
+
|
| 131 |
+
* Fix issue with forward references in parent `TypedDict` classes by [@Viicos](https://github.com/Viicos) in [#12427](https://github.com/pydantic/pydantic/pull/12427).
|
| 132 |
+
|
| 133 |
+
This issue is only relevant on Python 3.14 and greater.
|
| 134 |
+
* Exclude fields with `exclude_if` from JSON Schema required fields by [@Viicos](https://github.com/Viicos) in [#12430](https://github.com/pydantic/pydantic/pull/12430)
|
| 135 |
+
* Revert URL percent-encoding of credentials in the `build()` method
|
| 136 |
+
of the [`AnyUrl` and Dsn types](https://docs.pydantic.dev/latest/api/networks/) by [@davidhewitt](https://github.com/davidhewitt) in
|
| 137 |
+
[pydantic-core#1833](https://github.com/pydantic/pydantic-core/pull/1833).
|
| 138 |
+
|
| 139 |
+
This was initially considered as a bugfix, but caused regressions and as such was fully reverted. The next release will include
|
| 140 |
+
an opt-in option to percent-encode components of the URL.
|
| 141 |
+
* Add type inference for IP address types by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1868](https://github.com/pydantic/pydantic-core/pull/1868).
|
| 142 |
+
|
| 143 |
+
The 2.12 changes to the `serialize_as_any` behavior made it so that IP address types could not properly serialize to JSON.
|
| 144 |
+
* Avoid getting default values from defaultdict by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1853](https://github.com/pydantic/pydantic-core/pull/1853).
|
| 145 |
+
|
| 146 |
+
This fixes a subtle regression in the validation behavior of the [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict)
|
| 147 |
+
type.
|
| 148 |
+
* Fix issue with field serializers on nested typed dictionaries by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1879](https://github.com/pydantic/pydantic-core/pull/1879).
|
| 149 |
+
* Add more `pydantic-core` builds for the three-threaded version of Python 3.14 by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1864](https://github.com/pydantic/pydantic-core/pull/1864).
|
| 150 |
+
|
| 151 |
+
## v2.12.3 (2025-10-17)
|
| 152 |
+
|
| 153 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.3)
|
| 154 |
+
|
| 155 |
+
### What's Changed
|
| 156 |
+
|
| 157 |
+
This is the third 2.12 patch release, fixing issues related to the `FieldInfo` class, and reverting a change to the supported
|
| 158 |
+
[*after* model validator](https://docs.pydantic.dev/latest/concepts/validators/#model-validators) function signatures.
|
| 159 |
+
|
| 160 |
+
* Raise a warning when an invalid after model validator function signature is raised by [@Viicos](https://github.com/Viicos) in [#12414](https://github.com/pydantic/pydantic/pull/12414).
|
| 161 |
+
Starting in 2.12.0, using class methods for *after* model validators raised an error, but the error wasn't raised concistently. We decided
|
| 162 |
+
to emit a deprecation warning instead.
|
| 163 |
+
* Add [`FieldInfo.asdict()`](https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.FieldInfo.asdict) method, improve documentation around `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#12411](https://github.com/pydantic/pydantic/pull/12411).
|
| 164 |
+
This also add back support for mutations on `FieldInfo` classes, that are reused as `Annotated` metadata. **However**, note that this is still
|
| 165 |
+
*not* a supported pattern. Instead, please refer to the [added example](https://docs.pydantic.dev/latest/examples/dynamic_models/) in the documentation.
|
| 166 |
+
|
| 167 |
+
The [blog post](https://pydantic.dev/articles/pydantic-v2-12-release#changes) section on changes was also updated to document the changes related to `serialize_as_any`.
|
| 168 |
+
|
| 169 |
+
## v2.12.2 (2025-10-14)
|
| 170 |
+
|
| 171 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.2)
|
| 172 |
+
|
| 173 |
+
### What's Changed
|
| 174 |
+
|
| 175 |
+
#### Fixes
|
| 176 |
+
|
| 177 |
+
* Release a new `pydantic-core` version, as a corrupted CPython 3.10 `manylinux2014_aarch64` wheel got uploaded ([pydantic-core#1843](https://github.com/pydantic/pydantic-core/pull/1843)).
|
| 178 |
+
* Fix issue with recursive generic models with a parent model class by [@Viicos](https://github.com/Viicos) in [#12398](https://github.com/pydantic/pydantic/pull/12398)
|
| 179 |
+
|
| 180 |
+
## v2.12.1 (2025-10-13)
|
| 181 |
+
|
| 182 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.1)
|
| 183 |
+
|
| 184 |
+
### What's Changed
|
| 185 |
+
|
| 186 |
+
This is the first 2.12 patch release, addressing most (but not all yet) regressions from the initial 2.12.0 release.
|
| 187 |
+
|
| 188 |
+
#### Fixes
|
| 189 |
+
|
| 190 |
+
* Do not evaluate annotations when inspecting validators and serializers by [@Viicos](https://github.com/Viicos) in [#12355](https://github.com/pydantic/pydantic/pull/12355)
|
| 191 |
+
* Make sure `None` is converted as `NoneType` in Python 3.14 by [@Viicos](https://github.com/Viicos) in [#12370](https://github.com/pydantic/pydantic/pull/12370)
|
| 192 |
+
* Backport V1 runtime warning when using Python 3.14 by [@Viicos](https://github.com/Viicos) in [#12367](https://github.com/pydantic/pydantic/pull/12367)
|
| 193 |
+
* Fix error message for invalid validator signatures by [@Viicos](https://github.com/Viicos) in [#12366](https://github.com/pydantic/pydantic/pull/12366)
|
| 194 |
+
* Populate field name in `ValidationInfo` for validation of default value by [@Viicos](https://github.com/Viicos) in [pydantic-core#1826](https://github.com/pydantic/pydantic-core/pull/1826)
|
| 195 |
+
* Encode credentials in `MultiHostUrl` builder by [@willswire](https://github.com/willswire) in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
|
| 196 |
+
* Respect field serializers when using `serialize_as_any` serialization flag by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
|
| 197 |
+
* Fix various `RootModel` serialization issues by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1836](https://github.com/pydantic/pydantic-core/pull/1836)
|
| 198 |
+
|
| 199 |
+
### New Contributors
|
| 200 |
+
|
| 201 |
+
* [@willswire](https://github.com/willswire) made their first contribution in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
|
| 202 |
+
|
| 203 |
+
## v2.12.0 (2025-10-07)
|
| 204 |
+
|
| 205 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0)
|
| 206 |
+
|
| 207 |
+
### What's Changed
|
| 208 |
+
|
| 209 |
+
This is the final 2.12 release. It features the work of 20 external contributors and provides useful new features, along with initial Python 3.14 support.
|
| 210 |
+
Several minor changes (considered non-breaking changes according to our [versioning policy](https://docs.pydantic.dev/2.12/version-policy/#pydantic-v2))
|
| 211 |
+
are also included in this release. Make sure to look into them before upgrading.
|
| 212 |
+
|
| 213 |
+
**Note that Pydantic V1 is not compatible with Python 3.14 and greater**.
|
| 214 |
+
|
| 215 |
+
Changes (see the alpha and beta releases for additional changes since 2.11):
|
| 216 |
+
|
| 217 |
+
#### Packaging
|
| 218 |
+
|
| 219 |
+
* Update V1 copy to v1.10.24 by [@Viicos](https://github.com/Viicos) in [#12338](https://github.com/pydantic/pydantic/pull/12338)
|
| 220 |
+
|
| 221 |
+
#### New Features
|
| 222 |
+
|
| 223 |
+
* Add `extra` parameter to the validate functions by [@anvilpete](https://github.com/anvilpete) in [#12233](https://github.com/pydantic/pydantic/pull/12233)
|
| 224 |
+
* Add `exclude_computed_fields` serialization option by [@Viicos](https://github.com/Viicos) in [#12334](https://github.com/pydantic/pydantic/pull/12334)
|
| 225 |
+
* Add `preverse_empty_path` URL options by [@Viicos](https://github.com/Viicos) in [#12336](https://github.com/pydantic/pydantic/pull/12336)
|
| 226 |
+
* Add `union_format` parameter to JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#12147](https://github.com/pydantic/pydantic/pull/12147)
|
| 227 |
+
* Add `__qualname__` parameter for `create_model` by [@Atry](https://github.com/Atry) in [#12001](https://github.com/pydantic/pydantic/pull/12001)
|
| 228 |
+
|
| 229 |
+
#### Fixes
|
| 230 |
+
|
| 231 |
+
* Do not try to infer name from lambda definitions in pipelines API by [@Viicos](https://github.com/Viicos) in [#12289](https://github.com/pydantic/pydantic/pull/12289)
|
| 232 |
+
* Use proper namespace for functions in `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#12324](https://github.com/pydantic/pydantic/pull/12324)
|
| 233 |
+
* Use `Any` for context type annotation in `TypeAdapter` by [@inducer](https://github.com/inducer) in [#12279](https://github.com/pydantic/pydantic/pull/12279)
|
| 234 |
+
* Expose `FieldInfo` in `pydantic.fields.__all__` by [@Viicos](https://github.com/Viicos) in [#12339](https://github.com/pydantic/pydantic/pull/12339)
|
| 235 |
+
* Respect `validation_alias` in `@validate_call` by [@Viicos](https://github.com/Viicos) in [#12340](https://github.com/pydantic/pydantic/pull/12340)
|
| 236 |
+
* Use `Any` as context annotation in plugin API by [@Viicos](https://github.com/Viicos) in [#12341](https://github.com/pydantic/pydantic/pull/12341)
|
| 237 |
+
* Use proper `stacklevel` in warnings when possible by [@Viicos](https://github.com/Viicos) in [#12342](https://github.com/pydantic/pydantic/pull/12342)
|
| 238 |
+
|
| 239 |
+
### New Contributors
|
| 240 |
+
|
| 241 |
+
* [@anvilpete](https://github.com/anvilpete) made their first contribution in [#12233](https://github.com/pydantic/pydantic/pull/12233)
|
| 242 |
+
* [@JonathanWindell](https://github.com/JonathanWindell) made their first contribution in [#12327](https://github.com/pydantic/pydantic/pull/12327)
|
| 243 |
+
* [@inducer](https://github.com/inducer) made their first contribution in [#12279](https://github.com/pydantic/pydantic/pull/12279)
|
| 244 |
+
* [@Atry](https://github.com/Atry) made their first contribution in [#12001](https://github.com/pydantic/pydantic/pull/12001)
|
| 245 |
+
|
| 246 |
+
## v2.12.0b1 (2025-10-03)
|
| 247 |
+
|
| 248 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0b1)
|
| 249 |
+
|
| 250 |
+
This is the first beta release of the upcoming 2.12 release.
|
| 251 |
+
|
| 252 |
+
### What's Changed
|
| 253 |
+
|
| 254 |
+
#### Packaging
|
| 255 |
+
|
| 256 |
+
* Bump `pydantic-core` to v2.40.1 by [@Viicos](https://github.com/Viicos) in [#12314](https://github.com/pydantic/pydantic/pull/12314)
|
| 257 |
+
|
| 258 |
+
#### New Features
|
| 259 |
+
|
| 260 |
+
* Add support for `exclude_if` at the field level by [@andresliszt](https://github.com/andresliszt) in [#12141](https://github.com/pydantic/pydantic/pull/12141)
|
| 261 |
+
* Add `ValidateAs` annotation helper by [@Viicos](https://github.com/Viicos) in [#11942](https://github.com/pydantic/pydantic/pull/11942)
|
| 262 |
+
* Add configuration options for validation and JSON serialization of temporal types by [@ollz272](https://github.com/ollz272) in [#12068](https://github.com/pydantic/pydantic/pull/12068)
|
| 263 |
+
* Add support for PEP 728 by [@Viicos](https://github.com/Viicos) in [#12179](https://github.com/pydantic/pydantic/pull/12179)
|
| 264 |
+
* Add field name in serialization error by [@NicolasPllr1](https://github.com/NicolasPllr1) in [pydantic-core#1799](https://github.com/pydantic/pydantic-core/pull/1799)
|
| 265 |
+
* Add option to preserve empty URL paths by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1789](https://github.com/pydantic/pydantic-core/pull/1789)
|
| 266 |
+
|
| 267 |
+
#### Changes
|
| 268 |
+
|
| 269 |
+
* Raise error if an incompatible `pydantic-core` version is installed by [@Viicos](https://github.com/Viicos) in [#12196](https://github.com/pydantic/pydantic/pull/12196)
|
| 270 |
+
* Remove runtime warning for experimental features by [@Viicos](https://github.com/Viicos) in [#12265](https://github.com/pydantic/pydantic/pull/12265)
|
| 271 |
+
* Warn if registering virtual subclasses on Pydantic models by [@Viicos](https://github.com/Viicos) in [#11669](https://github.com/pydantic/pydantic/pull/11669)
|
| 272 |
+
|
| 273 |
+
#### Fixes
|
| 274 |
+
|
| 275 |
+
* Fix `__getattr__()` behavior on Pydantic models when a property raised an `AttributeError` and extra values are present by [@raspuchin](https://github.com/raspuchin) in [#12106](https://github.com/pydantic/pydantic/pull/12106)
|
| 276 |
+
* Add test to prevent regression with Pydantic models used as annotated metadata by [@Viicos](https://github.com/Viicos) in [#12133](https://github.com/pydantic/pydantic/pull/12133)
|
| 277 |
+
* Allow to use property setters on Pydantic dataclasses with `validate_assignment` set by [@Viicos](https://github.com/Viicos) in [#12173](https://github.com/pydantic/pydantic/pull/12173)
|
| 278 |
+
* Fix mypy v2 plugin for upcoming mypy release by [@cdce8p](https://github.com/cdce8p) in [#12209](https://github.com/pydantic/pydantic/pull/12209)
|
| 279 |
+
* Respect custom title in functions JSON Schema by [@Viicos](https://github.com/Viicos) in [#11892](https://github.com/pydantic/pydantic/pull/11892)
|
| 280 |
+
* Fix `ImportString` JSON serialization for objects with a `name` attribute by [@chr1sj0nes](https://github.com/chr1sj0nes) in [#12219](https://github.com/pydantic/pydantic/pull/12219)
|
| 281 |
+
* Do not error on fields overridden by methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#12290](https://github.com/pydantic/pydantic/pull/12290)
|
| 282 |
+
|
| 283 |
+
### New Contributors
|
| 284 |
+
|
| 285 |
+
* [@raspuchin](https://github.com/raspuchin) made their first contribution in [#12106](https://github.com/pydantic/pydantic/pull/12106)
|
| 286 |
+
* [@chr1sj0nes](https://github.com/chr1sj0nes) made their first contribution in [#12219](https://github.com/pydantic/pydantic/pull/12219)
|
| 287 |
+
|
| 288 |
+
## v2.12.0a1 (2025-07-26)
|
| 289 |
+
|
| 290 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0a1)
|
| 291 |
+
|
| 292 |
+
This is the first alpha release of the upcoming 2.12 release, which adds initial support for Python 3.14.
|
| 293 |
+
|
| 294 |
+
### What's Changed
|
| 295 |
+
|
| 296 |
+
#### New Features
|
| 297 |
+
|
| 298 |
+
* Add `__pydantic_on_complete__()` hook that is called once model is fully ready to be used by [@DouweM](https://github.com/DouweM) in [#11762](https://github.com/pydantic/pydantic/pull/11762)
|
| 299 |
+
* Add initial support for Python 3.14 by [@Viicos](https://github.com/Viicos) in [#11991](https://github.com/pydantic/pydantic/pull/11991)
|
| 300 |
+
* Add regex patterns to JSON schema for `Decimal` type by [@Dima-Bulavenko](https://github.com/Dima-Bulavenko) in [#11987](https://github.com/pydantic/pydantic/pull/11987)
|
| 301 |
+
* Add support for `doc` attribute on dataclass fields by [@Viicos](https://github.com/Viicos) in [#12077](https://github.com/pydantic/pydantic/pull/12077)
|
| 302 |
+
* Add experimental `MISSING` sentinel by [@Viicos](https://github.com/Viicos) in [#11883](https://github.com/pydantic/pydantic/pull/11883)
|
| 303 |
+
|
| 304 |
+
#### Changes
|
| 305 |
+
|
| 306 |
+
* Allow config and bases to be specified together in `create_model()` by [@Viicos](https://github.com/Viicos) in [#11714](https://github.com/pydantic/pydantic/pull/11714)
|
| 307 |
+
* Move some field logic out of the `GenerateSchema` class by [@Viicos](https://github.com/Viicos) in [#11733](https://github.com/pydantic/pydantic/pull/11733)
|
| 308 |
+
* Always make use of `inspect.getsourcelines()` for docstring extraction on Python 3.13 and greater by [@Viicos](https://github.com/Viicos) in [#11829](https://github.com/pydantic/pydantic/pull/11829)
|
| 309 |
+
* Only support the latest Mypy version by [@Viicos](https://github.com/Viicos) in [#11832](https://github.com/pydantic/pydantic/pull/11832)
|
| 310 |
+
* Do not implicitly convert after model validators to class methods by [@Viicos](https://github.com/Viicos) in [#11957](https://github.com/pydantic/pydantic/pull/11957)
|
| 311 |
+
* Refactor `FieldInfo` creation implementation by [@Viicos](https://github.com/Viicos) in [#11898](https://github.com/pydantic/pydantic/pull/11898)
|
| 312 |
+
* Make `Secret` covariant by [@bluenote10](https://github.com/bluenote10) in [#12008](https://github.com/pydantic/pydantic/pull/12008)
|
| 313 |
+
* Emit warning when field-specific metadata is used in invalid contexts by [@Viicos](https://github.com/Viicos) in [#12028](https://github.com/pydantic/pydantic/pull/12028)
|
| 314 |
+
|
| 315 |
+
#### Fixes
|
| 316 |
+
|
| 317 |
+
* Properly fetch plain serializer function when serializing default value in JSON Schema by [@Viicos](https://github.com/Viicos) in [#11721](https://github.com/pydantic/pydantic/pull/11721)
|
| 318 |
+
* Remove generics cache workaround by [@Viicos](https://github.com/Viicos) in [#11755](https://github.com/pydantic/pydantic/pull/11755)
|
| 319 |
+
* Remove coercion of decimal constraints by [@Viicos](https://github.com/Viicos) in [#11772](https://github.com/pydantic/pydantic/pull/11772)
|
| 320 |
+
* Fix crash when expanding root type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11735](https://github.com/pydantic/pydantic/pull/11735)
|
| 321 |
+
* Only mark model as complete once all fields are complete by [@DouweM](https://github.com/DouweM) in [#11759](https://github.com/pydantic/pydantic/pull/11759)
|
| 322 |
+
* Do not provide `field_name` in validator core schemas by [@DouweM](https://github.com/DouweM) in [#11761](https://github.com/pydantic/pydantic/pull/11761)
|
| 323 |
+
* Fix issue with recursive generic models by [@Viicos](https://github.com/Viicos) in [#11775](https://github.com/pydantic/pydantic/pull/11775)
|
| 324 |
+
* Fix qualified name comparison of private attributes during namespace inspection by [@karta9821](https://github.com/karta9821) in [#11803](https://github.com/pydantic/pydantic/pull/11803)
|
| 325 |
+
* Make sure Pydantic dataclasses with slots and `validate_assignment` can be unpickled by [@Viicos](https://github.com/Viicos) in [#11769](https://github.com/pydantic/pydantic/pull/11769)
|
| 326 |
+
* Traverse `function-before` schemas during schema gathering by [@Viicos](https://github.com/Viicos) in [#11801](https://github.com/pydantic/pydantic/pull/11801)
|
| 327 |
+
* Fix check for stdlib dataclasses by [@Viicos](https://github.com/Viicos) in [#11822](https://github.com/pydantic/pydantic/pull/11822)
|
| 328 |
+
* Check if `FieldInfo` is complete after applying type variable map by [@Viicos](https://github.com/Viicos) in [#11855](https://github.com/pydantic/pydantic/pull/11855)
|
| 329 |
+
* Do not delete mock validator/serializer in `model_rebuild()` by [@Viicos](https://github.com/Viicos) in [#11890](https://github.com/pydantic/pydantic/pull/11890)
|
| 330 |
+
* Rebuild dataclass fields before schema generation by [@Viicos](https://github.com/Viicos) in [#11949](https://github.com/pydantic/pydantic/pull/11949)
|
| 331 |
+
* Always store the original field assignment on `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11946](https://github.com/pydantic/pydantic/pull/11946)
|
| 332 |
+
* Do not use deprecated methods as default field values by [@Viicos](https://github.com/Viicos) in [#11914](https://github.com/pydantic/pydantic/pull/11914)
|
| 333 |
+
* Allow callable discriminator to be applied on PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in [#11941](https://github.com/pydantic/pydantic/pull/11941)
|
| 334 |
+
* Suppress core schema generation warning when using `SkipValidation` by [@ygsh0816](https://github.com/ygsh0816) in [#12002](https://github.com/pydantic/pydantic/pull/12002)
|
| 335 |
+
* Do not emit typechecking error for invalid `Field()` default with `validate_default` set to `True` by [@Viicos](https://github.com/Viicos) in [#11988](https://github.com/pydantic/pydantic/pull/11988)
|
| 336 |
+
* Refactor logic to support Pydantic's `Field()` function in dataclasses by [@Viicos](https://github.com/Viicos) in [#12051](https://github.com/pydantic/pydantic/pull/12051)
|
| 337 |
+
|
| 338 |
+
#### Packaging
|
| 339 |
+
|
| 340 |
+
* Update project metadata to use PEP 639 by [@Viicos](https://github.com/Viicos) in [#11694](https://github.com/pydantic/pydantic/pull/11694)
|
| 341 |
+
* Bump `mkdocs-llmstxt` to v0.2.0 by [@Viicos](https://github.com/Viicos) in [#11725](https://github.com/pydantic/pydantic/pull/11725)
|
| 342 |
+
* Bump `pydantic-core` to v2.35.1 by [@Viicos](https://github.com/Viicos) in [#11963](https://github.com/pydantic/pydantic/pull/11963)
|
| 343 |
+
* Bump dawidd6/action-download-artifact from 10 to 11 by [@dependabot](https://github.com/dependabot)[bot] in [#12033](https://github.com/pydantic/pydantic/pull/12033)
|
| 344 |
+
* Bump astral-sh/setup-uv from 5 to 6 by [@dependabot](https://github.com/dependabot)[bot] in [#11826](https://github.com/pydantic/pydantic/pull/11826)
|
| 345 |
+
* Update mypy to 1.17.0 by [@Viicos](https://github.com/Viicos) in [#12076](https://github.com/pydantic/pydantic/pull/12076)
|
| 346 |
+
|
| 347 |
+
### New Contributors
|
| 348 |
+
|
| 349 |
+
* [@parth-paradkar](https://github.com/parth-paradkar) made their first contribution in [#11695](https://github.com/pydantic/pydantic/pull/11695)
|
| 350 |
+
* [@dqkqd](https://github.com/dqkqd) made their first contribution in [#11739](https://github.com/pydantic/pydantic/pull/11739)
|
| 351 |
+
* [@fhightower](https://github.com/fhightower) made their first contribution in [#11722](https://github.com/pydantic/pydantic/pull/11722)
|
| 352 |
+
* [@gbaian10](https://github.com/gbaian10) made their first contribution in [#11766](https://github.com/pydantic/pydantic/pull/11766)
|
| 353 |
+
* [@DouweM](https://github.com/DouweM) made their first contribution in [#11759](https://github.com/pydantic/pydantic/pull/11759)
|
| 354 |
+
* [@bowenliang123](https://github.com/bowenliang123) made their first contribution in [#11719](https://github.com/pydantic/pydantic/pull/11719)
|
| 355 |
+
* [@rawwar](https://github.com/rawwar) made their first contribution in [#11799](https://github.com/pydantic/pydantic/pull/11799)
|
| 356 |
+
* [@karta9821](https://github.com/karta9821) made their first contribution in [#11803](https://github.com/pydantic/pydantic/pull/11803)
|
| 357 |
+
* [@jinnovation](https://github.com/jinnovation) made their first contribution in [#11834](https://github.com/pydantic/pydantic/pull/11834)
|
| 358 |
+
* [@zmievsa](https://github.com/zmievsa) made their first contribution in [#11861](https://github.com/pydantic/pydantic/pull/11861)
|
| 359 |
+
* [@Otto-AA](https://github.com/Otto-AA) made their first contribution in [#11860](https://github.com/pydantic/pydantic/pull/11860)
|
| 360 |
+
* [@ygsh0816](https://github.com/ygsh0816) made their first contribution in [#12002](https://github.com/pydantic/pydantic/pull/12002)
|
| 361 |
+
* [@lukland](https://github.com/lukland) made their first contribution in [#12015](https://github.com/pydantic/pydantic/pull/12015)
|
| 362 |
+
* [@Dima-Bulavenko](https://github.com/Dima-Bulavenko) made their first contribution in [#11987](https://github.com/pydantic/pydantic/pull/11987)
|
| 363 |
+
* [@GSemikozov](https://github.com/GSemikozov) made their first contribution in [#12050](https://github.com/pydantic/pydantic/pull/12050)
|
| 364 |
+
* [@hannah-heywa](https://github.com/hannah-heywa) made their first contribution in [#12082](https://github.com/pydantic/pydantic/pull/12082)
|
| 365 |
+
|
| 366 |
+
## v2.11.7 (2025-06-14)
|
| 367 |
+
|
| 368 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.7)
|
| 369 |
+
|
| 370 |
+
### What's Changed
|
| 371 |
+
|
| 372 |
+
#### Fixes
|
| 373 |
+
|
| 374 |
+
* Copy `FieldInfo` instance if necessary during `FieldInfo` build by [@Viicos](https://github.com/Viicos) in [#11898](https://github.com/pydantic/pydantic/pull/11898)
|
| 375 |
+
|
| 376 |
+
## v2.11.6 (2025-06-13)
|
| 377 |
+
|
| 378 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.6)
|
| 379 |
+
|
| 380 |
+
### What's Changed
|
| 381 |
+
|
| 382 |
+
#### Fixes
|
| 383 |
+
|
| 384 |
+
* Rebuild dataclass fields before schema generation by [@Viicos](https://github.com/Viicos) in [#11949](https://github.com/pydantic/pydantic/pull/11949)
|
| 385 |
+
* Always store the original field assignment on `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11946](https://github.com/pydantic/pydantic/pull/11946)
|
| 386 |
+
|
| 387 |
+
## v2.11.5 (2025-05-22)
|
| 388 |
+
|
| 389 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.5)
|
| 390 |
+
|
| 391 |
+
### What's Changed
|
| 392 |
+
|
| 393 |
+
#### Fixes
|
| 394 |
+
|
| 395 |
+
* Check if `FieldInfo` is complete after applying type variable map by [@Viicos](https://github.com/Viicos) in [#11855](https://github.com/pydantic/pydantic/pull/11855)
|
| 396 |
+
* Do not delete mock validator/serializer in `model_rebuild()` by [@Viicos](https://github.com/Viicos) in [#11890](https://github.com/pydantic/pydantic/pull/11890)
|
| 397 |
+
* Do not duplicate metadata on model rebuild by [@Viicos](https://github.com/Viicos) in [#11902](https://github.com/pydantic/pydantic/pull/11902)
|
| 398 |
+
|
| 399 |
+
## v2.11.4 (2025-04-29)
|
| 400 |
+
|
| 401 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.4)
|
| 402 |
+
|
| 403 |
+
### What's Changed
|
| 404 |
+
|
| 405 |
+
#### Packaging
|
| 406 |
+
|
| 407 |
+
* Bump `mkdocs-llmstxt` to v0.2.0 by [@Viicos](https://github.com/Viicos) in [#11725](https://github.com/pydantic/pydantic/pull/11725)
|
| 408 |
+
|
| 409 |
+
#### Changes
|
| 410 |
+
|
| 411 |
+
* Allow config and bases to be specified together in `create_model()` by [@Viicos](https://github.com/Viicos) in [#11714](https://github.com/pydantic/pydantic/pull/11714).
|
| 412 |
+
This change was backported as it was previously possible (although not meant to be supported)
|
| 413 |
+
to provide `model_config` as a field, which would make it possible to provide both configuration
|
| 414 |
+
and bases.
|
| 415 |
+
|
| 416 |
+
#### Fixes
|
| 417 |
+
|
| 418 |
+
* Remove generics cache workaround by [@Viicos](https://github.com/Viicos) in [#11755](https://github.com/pydantic/pydantic/pull/11755)
|
| 419 |
+
* Remove coercion of decimal constraints by [@Viicos](https://github.com/Viicos) in [#11772](https://github.com/pydantic/pydantic/pull/11772)
|
| 420 |
+
* Fix crash when expanding root type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11735](https://github.com/pydantic/pydantic/pull/11735)
|
| 421 |
+
* Fix issue with recursive generic models by [@Viicos](https://github.com/Viicos) in [#11775](https://github.com/pydantic/pydantic/pull/11775)
|
| 422 |
+
* Traverse `function-before` schemas during schema gathering by [@Viicos](https://github.com/Viicos) in [#11801](https://github.com/pydantic/pydantic/pull/11801)
|
| 423 |
+
|
| 424 |
+
## v2.11.3 (2025-04-08)
|
| 425 |
+
|
| 426 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.3)
|
| 427 |
+
|
| 428 |
+
### What's Changed
|
| 429 |
+
|
| 430 |
+
#### Packaging
|
| 431 |
+
|
| 432 |
+
* Update V1 copy to v1.10.21 by [@Viicos](https://github.com/Viicos) in [#11706](https://github.com/pydantic/pydantic/pull/11706)
|
| 433 |
+
|
| 434 |
+
#### Fixes
|
| 435 |
+
|
| 436 |
+
* Preserve field description when rebuilding model fields by [@Viicos](https://github.com/Viicos) in [#11698](https://github.com/pydantic/pydantic/pull/11698)
|
| 437 |
+
|
| 438 |
+
## v2.11.2 (2025-04-03)
|
| 439 |
+
|
| 440 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.2)
|
| 441 |
+
|
| 442 |
+
### What's Changed
|
| 443 |
+
|
| 444 |
+
#### Fixes
|
| 445 |
+
|
| 446 |
+
* Bump `pydantic-core` to v2.33.1 by [@Viicos](https://github.com/Viicos) in [#11678](https://github.com/pydantic/pydantic/pull/11678)
|
| 447 |
+
* Make sure `__pydantic_private__` exists before setting private attributes by [@Viicos](https://github.com/Viicos) in [#11666](https://github.com/pydantic/pydantic/pull/11666)
|
| 448 |
+
* Do not override `FieldInfo._complete` when using field from parent class by [@Viicos](https://github.com/Viicos) in [#11668](https://github.com/pydantic/pydantic/pull/11668)
|
| 449 |
+
* Provide the available definitions when applying discriminated unions by [@Viicos](https://github.com/Viicos) in [#11670](https://github.com/pydantic/pydantic/pull/11670)
|
| 450 |
+
* Do not expand root type in the mypy plugin for variables by [@Viicos](https://github.com/Viicos) in [#11676](https://github.com/pydantic/pydantic/pull/11676)
|
| 451 |
+
* Mention the attribute name in model fields deprecation message by [@Viicos](https://github.com/Viicos) in [#11674](https://github.com/pydantic/pydantic/pull/11674)
|
| 452 |
+
* Properly validate parameterized mappings by [@Viicos](https://github.com/Viicos) in [#11658](https://github.com/pydantic/pydantic/pull/11658)
|
| 453 |
+
|
| 454 |
+
## v2.11.1 (2025-03-28)
|
| 455 |
+
|
| 456 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.1)
|
| 457 |
+
|
| 458 |
+
### What's Changed
|
| 459 |
+
|
| 460 |
+
#### Fixes
|
| 461 |
+
|
| 462 |
+
* Do not override `'definitions-ref'` schemas containing serialization schemas or metadata by [@Viicos](https://github.com/Viicos) in [#11644](https://github.com/pydantic/pydantic/pull/11644)
|
| 463 |
+
|
| 464 |
+
## v2.11.0 (2025-03-27)
|
| 465 |
+
|
| 466 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0)
|
| 467 |
+
|
| 468 |
+
### What's Changed
|
| 469 |
+
|
| 470 |
+
Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
|
| 471 |
+
See the [blog post](https://pydantic.dev/articles/pydantic-v2-11-release) for more details.
|
| 472 |
+
|
| 473 |
+
#### Packaging
|
| 474 |
+
|
| 475 |
+
* Bump `pydantic-core` to v2.33.0 by [@Viicos](https://github.com/Viicos) in [#11631](https://github.com/pydantic/pydantic/pull/11631)
|
| 476 |
+
|
| 477 |
+
#### New Features
|
| 478 |
+
|
| 479 |
+
* Add `encoded_string()` method to the URL types by [@YassinNouh21](https://github.com/YassinNouh21) in [#11580](https://github.com/pydantic/pydantic/pull/11580)
|
| 480 |
+
* Add support for `defer_build` with `@validate_call` decorator by [@Viicos](https://github.com/Viicos) in [#11584](https://github.com/pydantic/pydantic/pull/11584)
|
| 481 |
+
* Allow `@with_config` decorator to be used with keyword arguments by [@Viicos](https://github.com/Viicos) in [#11608](https://github.com/pydantic/pydantic/pull/11608)
|
| 482 |
+
* Simplify customization of default value inclusion in JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#11634](https://github.com/pydantic/pydantic/pull/11634)
|
| 483 |
+
* Add `generate_arguments_schema()` function by [@Viicos](https://github.com/Viicos) in [#11572](https://github.com/pydantic/pydantic/pull/11572)
|
| 484 |
+
|
| 485 |
+
#### Fixes
|
| 486 |
+
|
| 487 |
+
* Allow generic typed dictionaries to be used for unpacked variadic keyword parameters by [@Viicos](https://github.com/Viicos) in [#11571](https://github.com/pydantic/pydantic/pull/11571)
|
| 488 |
+
* Fix runtime error when computing model string representation involving cached properties and self-referenced models by [@Viicos](https://github.com/Viicos) in [#11579](https://github.com/pydantic/pydantic/pull/11579)
|
| 489 |
+
* Preserve other steps when using the ellipsis in the pipeline API by [@Viicos](https://github.com/Viicos) in [#11626](https://github.com/pydantic/pydantic/pull/11626)
|
| 490 |
+
* Fix deferred discriminator application logic by [@Viicos](https://github.com/Viicos) in [#11591](https://github.com/pydantic/pydantic/pull/11591)
|
| 491 |
+
|
| 492 |
+
### New Contributors
|
| 493 |
+
|
| 494 |
+
* [@cmenon12](https://github.com/cmenon12) made their first contribution in [#11562](https://github.com/pydantic/pydantic/pull/11562)
|
| 495 |
+
* [@Jeukoh](https://github.com/Jeukoh) made their first contribution in [#11611](https://github.com/pydantic/pydantic/pull/11611)
|
| 496 |
+
|
| 497 |
+
## v2.11.0b2 (2025-03-17)
|
| 498 |
+
|
| 499 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b2)
|
| 500 |
+
|
| 501 |
+
### What's Changed
|
| 502 |
+
|
| 503 |
+
#### Packaging
|
| 504 |
+
|
| 505 |
+
* Bump `pydantic-core` to v2.32.0 by [@Viicos](https://github.com/Viicos) in [#11567](https://github.com/pydantic/pydantic/pull/11567)
|
| 506 |
+
|
| 507 |
+
#### New Features
|
| 508 |
+
|
| 509 |
+
* Add experimental support for free threading by [@Viicos](https://github.com/Viicos) in [#11516](https://github.com/pydantic/pydantic/pull/11516)
|
| 510 |
+
|
| 511 |
+
#### Fixes
|
| 512 |
+
|
| 513 |
+
* Fix `NotRequired` qualifier not taken into account in stringified annotation by [@Viicos](https://github.com/Viicos) in [#11559](https://github.com/pydantic/pydantic/pull/11559)
|
| 514 |
+
|
| 515 |
+
### New Contributors
|
| 516 |
+
|
| 517 |
+
* [@joren485](https://github.com/joren485) made their first contribution in [#11547](https://github.com/pydantic/pydantic/pull/11547)
|
| 518 |
+
|
| 519 |
+
## v2.11.0b1 (2025-03-06)
|
| 520 |
+
|
| 521 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b1)
|
| 522 |
+
|
| 523 |
+
### What's Changed
|
| 524 |
+
|
| 525 |
+
#### Packaging
|
| 526 |
+
|
| 527 |
+
* Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11324
|
| 528 |
+
* Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11351
|
| 529 |
+
* Use the `typing-inspection` library by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11479
|
| 530 |
+
* Bump `pydantic-core` to `v2.31.1` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11526
|
| 531 |
+
|
| 532 |
+
#### New Features
|
| 533 |
+
|
| 534 |
+
* Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in https://github.com/pydantic/pydantic/pull/10789
|
| 535 |
+
* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11034
|
| 536 |
+
* Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11088
|
| 537 |
+
* Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11189
|
| 538 |
+
* Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11332
|
| 539 |
+
* Add support for validating v6, v7, v8 UUIDs by [@astei](https://github.com/astei) in https://github.com/pydantic/pydantic/pull/11436
|
| 540 |
+
* Improve alias configuration APIs by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11468
|
| 541 |
+
|
| 542 |
+
#### Changes
|
| 543 |
+
|
| 544 |
+
* Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11032
|
| 545 |
+
* Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11168
|
| 546 |
+
* Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11169
|
| 547 |
+
* **Breaking Change:** Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10846
|
| 548 |
+
* Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11258
|
| 549 |
+
* Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10863
|
| 550 |
+
* Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11271
|
| 551 |
+
|
| 552 |
+
#### Performance
|
| 553 |
+
|
| 554 |
+
* Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10769
|
| 555 |
+
* Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/10868
|
| 556 |
+
* Improve annotation application performance by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11186
|
| 557 |
+
* Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11255
|
| 558 |
+
* Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11244
|
| 559 |
+
* Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11384
|
| 560 |
+
* Bump `pydantic-core` and thus use `SchemaValidator` and `SchemaSerializer` caching by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11402
|
| 561 |
+
* Reuse cached core schemas for parametrized generic Pydantic models by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/11434
|
| 562 |
+
|
| 563 |
+
#### Fixes
|
| 564 |
+
|
| 565 |
+
* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10872
|
| 566 |
+
* Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10893
|
| 567 |
+
* Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11121
|
| 568 |
+
* Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11114
|
| 569 |
+
* Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11116
|
| 570 |
+
* Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11155
|
| 571 |
+
* Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11161
|
| 572 |
+
* Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11109
|
| 573 |
+
* Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11200
|
| 574 |
+
* Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in https://github.com/pydantic/pydantic/pull/11014
|
| 575 |
+
* Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10704
|
| 576 |
+
* Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11216
|
| 577 |
+
* Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11208
|
| 578 |
+
* Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11212
|
| 579 |
+
* Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11246
|
| 580 |
+
* Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11281
|
| 581 |
+
* Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11295
|
| 582 |
+
* Fix JSON Schema reference collection with `"examples"` keys by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11305
|
| 583 |
+
* Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11298
|
| 584 |
+
* Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11321
|
| 585 |
+
* Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in https://github.com/pydantic/pydantic/pull/11319
|
| 586 |
+
* Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11350
|
| 587 |
+
* Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11367
|
| 588 |
+
* Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11356
|
| 589 |
+
* Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in https://github.com/pydantic/pydantic/pull/11392
|
| 590 |
+
* Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11398
|
| 591 |
+
* Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11416
|
| 592 |
+
* Do not reuse validators and serializers during model rebuild by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11429
|
| 593 |
+
* Collect model fields when rebuilding a model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11388
|
| 594 |
+
* Allow cached properties to be altered on frozen models by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11432
|
| 595 |
+
* Fix tuple serialization for `Sequence` types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11435
|
| 596 |
+
* Fix: do not check for `__get_validators__` on classes where `__get_pydantic_core_schema__` is also defined by [@tlambert03](https://github.com/tlambert03) in https://github.com/pydantic/pydantic/pull/11444
|
| 597 |
+
* Allow callable instances to be used as serializers by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11451
|
| 598 |
+
* Improve error thrown when overriding field with a property by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11459
|
| 599 |
+
* Fix JSON Schema generation with referenceable core schemas holding JSON metadata by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11475
|
| 600 |
+
* Support strict specification on union member types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11481
|
| 601 |
+
* Implicitly set `validate_by_name` to `True` when `validate_by_alias` is `False` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11503
|
| 602 |
+
* Change type of `Any` when synthesizing `BaseSettings.__init__` signature in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11497
|
| 603 |
+
* Support type variable defaults referencing other type variables by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11520
|
| 604 |
+
* Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in https://github.com/pydantic/pydantic-core/pull/1583
|
| 605 |
+
* `dataclass` `InitVar` shouldn't be required on serialization by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic-core/pull/1602
|
| 606 |
+
|
| 607 |
+
## New Contributors
|
| 608 |
+
|
| 609 |
+
* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in https://github.com/pydantic/pydantic/pull/10789
|
| 610 |
+
* [@tamird](https://github.com/tamird) made their first contribution in https://github.com/pydantic/pydantic/pull/10948
|
| 611 |
+
* [@felixxm](https://github.com/felixxm) made their first contribution in https://github.com/pydantic/pydantic/pull/11077
|
| 612 |
+
* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in https://github.com/pydantic/pydantic/pull/11082
|
| 613 |
+
* [@Kharianne](https://github.com/Kharianne) made their first contribution in https://github.com/pydantic/pydantic/pull/11111
|
| 614 |
+
* [@mdaffad](https://github.com/mdaffad) made their first contribution in https://github.com/pydantic/pydantic/pull/11177
|
| 615 |
+
* [@thejcannon](https://github.com/thejcannon) made their first contribution in https://github.com/pydantic/pydantic/pull/11014
|
| 616 |
+
* [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in https://github.com/pydantic/pydantic/pull/11251
|
| 617 |
+
* [@usernameMAI](https://github.com/usernameMAI) made their first contribution in https://github.com/pydantic/pydantic/pull/11275
|
| 618 |
+
* [@ananiavito](https://github.com/ananiavito) made their first contribution in https://github.com/pydantic/pydantic/pull/11302
|
| 619 |
+
* [@pawamoy](https://github.com/pawamoy) made their first contribution in https://github.com/pydantic/pydantic/pull/11311
|
| 620 |
+
* [@Maze21127](https://github.com/Maze21127) made their first contribution in https://github.com/pydantic/pydantic/pull/11319
|
| 621 |
+
* [@kauabh](https://github.com/kauabh) made their first contribution in https://github.com/pydantic/pydantic/pull/11369
|
| 622 |
+
* [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in https://github.com/pydantic/pydantic/pull/11353
|
| 623 |
+
* [@tmpbeing](https://github.com/tmpbeing) made their first contribution in https://github.com/pydantic/pydantic/pull/11375
|
| 624 |
+
* [@petyosi](https://github.com/petyosi) made their first contribution in https://github.com/pydantic/pydantic/pull/11405
|
| 625 |
+
* [@austinyu](https://github.com/austinyu) made their first contribution in https://github.com/pydantic/pydantic/pull/11392
|
| 626 |
+
* [@mikeedjones](https://github.com/mikeedjones) made their first contribution in https://github.com/pydantic/pydantic/pull/11402
|
| 627 |
+
* [@astei](https://github.com/astei) made their first contribution in https://github.com/pydantic/pydantic/pull/11436
|
| 628 |
+
* [@dsayling](https://github.com/dsayling) made their first contribution in https://github.com/pydantic/pydantic/pull/11522
|
| 629 |
+
* [@sobolevn](https://github.com/sobolevn) made their first contribution in https://github.com/pydantic/pydantic-core/pull/1645
|
| 630 |
+
|
| 631 |
+
## v2.11.0a2 (2025-02-10)
|
| 632 |
+
|
| 633 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a2)
|
| 634 |
+
|
| 635 |
+
### What's Changed
|
| 636 |
+
|
| 637 |
+
Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
|
| 638 |
+
This is another early alpha release, meant to collect early feedback from users having issues with core schema builds.
|
| 639 |
+
|
| 640 |
+
#### Packaging
|
| 641 |
+
|
| 642 |
+
* Bump `ruff` from 0.9.2 to 0.9.5 by [@Viicos](https://github.com/Viicos) in [#11407](https://github.com/pydantic/pydantic/pull/11407)
|
| 643 |
+
* Bump `pydantic-core` to v2.29.0 by [@mikeedjones](https://github.com/mikeedjones) in [#11402](https://github.com/pydantic/pydantic/pull/11402)
|
| 644 |
+
* Use locally-built rust with symbols & pgo by [@davidhewitt](https://github.com/davidhewitt) in [#11403](https://github.com/pydantic/pydantic/pull/11403)
|
| 645 |
+
|
| 646 |
+
#### Performance
|
| 647 |
+
|
| 648 |
+
* Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in [#11384](https://github.com/pydantic/pydantic/pull/11384)
|
| 649 |
+
|
| 650 |
+
#### Fixes
|
| 651 |
+
|
| 652 |
+
* Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in [#11367](https://github.com/pydantic/pydantic/pull/11367)
|
| 653 |
+
* Fix JSON Schema reference logic with `examples` keys by [@Viicos](https://github.com/Viicos) in [#11366](https://github.com/pydantic/pydantic/pull/11366)
|
| 654 |
+
* Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in [#11356](https://github.com/pydantic/pydantic/pull/11356)
|
| 655 |
+
* Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in [#11392](https://github.com/pydantic/pydantic/pull/11392)
|
| 656 |
+
* Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in [#11398](https://github.com/pydantic/pydantic/pull/11398)
|
| 657 |
+
* Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11416](https://github.com/pydantic/pydantic/pull/11416)
|
| 658 |
+
|
| 659 |
+
### New Contributors
|
| 660 |
+
|
| 661 |
+
* [@kauabh](https://github.com/kauabh) made their first contribution in [#11369](https://github.com/pydantic/pydantic/pull/11369)
|
| 662 |
+
* [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in [#11353](https://github.com/pydantic/pydantic/pull/11353)
|
| 663 |
+
* [@tmpbeing](https://github.com/tmpbeing) made their first contribution in [#11375](https://github.com/pydantic/pydantic/pull/11375)
|
| 664 |
+
* [@petyosi](https://github.com/petyosi) made their first contribution in [#11405](https://github.com/pydantic/pydantic/pull/11405)
|
| 665 |
+
* [@austinyu](https://github.com/austinyu) made their first contribution in [#11392](https://github.com/pydantic/pydantic/pull/11392)
|
| 666 |
+
* [@mikeedjones](https://github.com/mikeedjones) made their first contribution in [#11402](https://github.com/pydantic/pydantic/pull/11402)
|
| 667 |
+
|
| 668 |
+
## v2.11.0a1 (2025-01-30)
|
| 669 |
+
|
| 670 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a1)
|
| 671 |
+
|
| 672 |
+
### What's Changed
|
| 673 |
+
|
| 674 |
+
Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
|
| 675 |
+
This is an early alpha release, meant to collect early feedback from users having issues with core schema builds.
|
| 676 |
+
|
| 677 |
+
#### Packaging
|
| 678 |
+
|
| 679 |
+
* Bump dawidd6/action-download-artifact from 6 to 7 by [@dependabot](https://github.com/dependabot) in [#11018](https://github.com/pydantic/pydantic/pull/11018)
|
| 680 |
+
* Re-enable memray related tests on Python 3.12+ by [@Viicos](https://github.com/Viicos) in [#11191](https://github.com/pydantic/pydantic/pull/11191)
|
| 681 |
+
* Bump astral-sh/setup-uv to 5 by [@dependabot](https://github.com/dependabot) in [#11205](https://github.com/pydantic/pydantic/pull/11205)
|
| 682 |
+
* Bump `ruff` to v0.9.0 by [@sydney-runkle](https://github.com/sydney-runkle) in [#11254](https://github.com/pydantic/pydantic/pull/11254)
|
| 683 |
+
* Regular `uv.lock` deps update by [@sydney-runkle](https://github.com/sydney-runkle) in [#11333](https://github.com/pydantic/pydantic/pull/11333)
|
| 684 |
+
* Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in [#11324](https://github.com/pydantic/pydantic/pull/11324)
|
| 685 |
+
* Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in [#11351](https://github.com/pydantic/pydantic/pull/11351)
|
| 686 |
+
* Bump `pydantic-core` to v2.28.0 by [@Viicos](https://github.com/Viicos) in [#11364](https://github.com/pydantic/pydantic/pull/11364)
|
| 687 |
+
|
| 688 |
+
#### New Features
|
| 689 |
+
|
| 690 |
+
* Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in [#10789](https://github.com/pydantic/pydantic/pull/10789)
|
| 691 |
+
* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034)
|
| 692 |
+
* Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in [#11088](https://github.com/pydantic/pydantic/pull/11088)
|
| 693 |
+
* Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in [#11189](https://github.com/pydantic/pydantic/pull/11189)
|
| 694 |
+
* Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in [#11332](https://github.com/pydantic/pydantic/pull/11332)
|
| 695 |
+
|
| 696 |
+
#### Changes
|
| 697 |
+
|
| 698 |
+
* Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in [#11032](https://github.com/pydantic/pydantic/pull/11032)
|
| 699 |
+
* Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in [#11168](https://github.com/pydantic/pydantic/pull/11168)
|
| 700 |
+
* Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in [#11169](https://github.com/pydantic/pydantic/pull/11169)
|
| 701 |
+
* Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10846](https://github.com/pydantic/pydantic/pull/10846)
|
| 702 |
+
* Move `deque` schema gen to `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#11239](https://github.com/pydantic/pydantic/pull/11239)
|
| 703 |
+
* Move `Mapping` schema gen to `GenerateSchema` to complete removal of `prepare_annotations_for_known_type` workaround by [@sydney-runkle](https://github.com/sydney-runkle) in [#11247](https://github.com/pydantic/pydantic/pull/11247)
|
| 704 |
+
* Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in [#11258](https://github.com/pydantic/pydantic/pull/11258)
|
| 705 |
+
* Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#11271](https://github.com/pydantic/pydantic/pull/11271)
|
| 706 |
+
|
| 707 |
+
#### Performance
|
| 708 |
+
|
| 709 |
+
* Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769)
|
| 710 |
+
* Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in [#10863](https://github.com/pydantic/pydantic/pull/10863)
|
| 711 |
+
* Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in [#10868](https://github.com/pydantic/pydantic/pull/10868)
|
| 712 |
+
* Improve annotation application performance by [@Viicos](https://github.com/Viicos) in [#11186](https://github.com/pydantic/pydantic/pull/11186)
|
| 713 |
+
* Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#11255](https://github.com/pydantic/pydantic/pull/11255)
|
| 714 |
+
* Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) and [@MarkusSintonen](https://github.com/MarkusSintonen) in [#11244](https://github.com/pydantic/pydantic/pull/11244)
|
| 715 |
+
|
| 716 |
+
#### Fixes
|
| 717 |
+
|
| 718 |
+
* Add validation tests for `_internal/_validators.py` by [@tkasuz](https://github.com/tkasuz) in [#10763](https://github.com/pydantic/pydantic/pull/10763)
|
| 719 |
+
* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872)
|
| 720 |
+
* Revert "ci: use locally built pydantic-core with debug symbols by [@sydney-runkle](https://github.com/sydney-runkle) in [#10942](https://github.com/pydantic/pydantic/pull/10942)
|
| 721 |
+
* Re-enable all FastAPI tests by [@tamird](https://github.com/tamird) in [#10948](https://github.com/pydantic/pydantic/pull/10948)
|
| 722 |
+
* Fix typo in HISTORY.md. by [@felixxm](https://github.com/felixxm) in [#11077](https://github.com/pydantic/pydantic/pull/11077)
|
| 723 |
+
* Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11121](https://github.com/pydantic/pydantic/pull/11121)
|
| 724 |
+
* Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in [#11114](https://github.com/pydantic/pydantic/pull/11114)
|
| 725 |
+
* Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in [#11116](https://github.com/pydantic/pydantic/pull/11116)
|
| 726 |
+
* Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in [#11155](https://github.com/pydantic/pydantic/pull/11155)
|
| 727 |
+
* Add FastAPI and SQLModel to third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11044](https://github.com/pydantic/pydantic/pull/11044)
|
| 728 |
+
* Fix conditional expressions syntax for third-party tests by [@Viicos](https://github.com/Viicos) in [#11162](https://github.com/pydantic/pydantic/pull/11162)
|
| 729 |
+
* Move FastAPI tests to third-party workflow by [@Viicos](https://github.com/Viicos) in [#11164](https://github.com/pydantic/pydantic/pull/11164)
|
| 730 |
+
* Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in [#11161](https://github.com/pydantic/pydantic/pull/11161)
|
| 731 |
+
* Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in [#11109](https://github.com/pydantic/pydantic/pull/11109)
|
| 732 |
+
* Include `openapi-python-client` check in issue creation for third-party failures, use `main` branch by [@sydney-runkle](https://github.com/sydney-runkle) in [#11182](https://github.com/pydantic/pydantic/pull/11182)
|
| 733 |
+
* Add pandera third-party tests by [@Viicos](https://github.com/Viicos) in [#11193](https://github.com/pydantic/pydantic/pull/11193)
|
| 734 |
+
* Add ODMantic third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11197](https://github.com/pydantic/pydantic/pull/11197)
|
| 735 |
+
* Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in [#11200](https://github.com/pydantic/pydantic/pull/11200)
|
| 736 |
+
* Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in [#11014](https://github.com/pydantic/pydantic/pull/11014)
|
| 737 |
+
* Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in [#10704](https://github.com/pydantic/pydantic/pull/10704)
|
| 738 |
+
* Re-enable Beanie third-party tests by [@Viicos](https://github.com/Viicos) in [#11214](https://github.com/pydantic/pydantic/pull/11214)
|
| 739 |
+
* Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in [#11216](https://github.com/pydantic/pydantic/pull/11216)
|
| 740 |
+
* Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in [#11208](https://github.com/pydantic/pydantic/pull/11208)
|
| 741 |
+
* Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11212](https://github.com/pydantic/pydantic/pull/11212)
|
| 742 |
+
* Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in [#11246](https://github.com/pydantic/pydantic/pull/11246)
|
| 743 |
+
* Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11281](https://github.com/pydantic/pydantic/pull/11281)
|
| 744 |
+
* Fix two misplaced sentences in validation errors documentation by [@ananiavito](https://github.com/ananiavito) in [#11302](https://github.com/pydantic/pydantic/pull/11302)
|
| 745 |
+
* Fix mkdocstrings inventory example in documentation by [@pawamoy](https://github.com/pawamoy) in [#11311](https://github.com/pydantic/pydantic/pull/11311)
|
| 746 |
+
* Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11295](https://github.com/pydantic/pydantic/pull/11295)
|
| 747 |
+
* Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11298](https://github.com/pydantic/pydantic/pull/11298)
|
| 748 |
+
* Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11321](https://github.com/pydantic/pydantic/pull/11321)
|
| 749 |
+
* Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in [#11319](https://github.com/pydantic/pydantic/pull/11319)
|
| 750 |
+
* Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in [#11350](https://github.com/pydantic/pydantic/pull/11350)
|
| 751 |
+
* Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1583](https://github.com/pydantic/pydantic-core/pull/1583)
|
| 752 |
+
|
| 753 |
+
### New Contributors
|
| 754 |
+
|
| 755 |
+
* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789)
|
| 756 |
+
* [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948)
|
| 757 |
+
* [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077)
|
| 758 |
+
* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082)
|
| 759 |
+
* [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111)
|
| 760 |
+
* [@mdaffad](https://github.com/mdaffad) made their first contribution in [#11177](https://github.com/pydantic/pydantic/pull/11177)
|
| 761 |
+
* [@thejcannon](https://github.com/thejcannon) made their first contribution in [#11014](https://github.com/pydantic/pydantic/pull/11014)
|
| 762 |
+
* [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in [#11251](https://github.com/pydantic/pydantic/pull/11251)
|
| 763 |
+
* [@usernameMAI](https://github.com/usernameMAI) made their first contribution in [#11275](https://github.com/pydantic/pydantic/pull/11275)
|
| 764 |
+
* [@ananiavito](https://github.com/ananiavito) made their first contribution in [#11302](https://github.com/pydantic/pydantic/pull/11302)
|
| 765 |
+
* [@pawamoy](https://github.com/pawamoy) made their first contribution in [#11311](https://github.com/pydantic/pydantic/pull/11311)
|
| 766 |
+
* [@Maze21127](https://github.com/Maze21127) made their first contribution in [#11319](https://github.com/pydantic/pydantic/pull/11319)
|
| 767 |
+
|
| 768 |
+
## v2.10.6 (2025-01-23)
|
| 769 |
+
|
| 770 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.6)
|
| 771 |
+
|
| 772 |
+
### What's Changed
|
| 773 |
+
|
| 774 |
+
#### Fixes
|
| 775 |
+
|
| 776 |
+
* Fix JSON Schema reference collection with `'examples'` keys by [@Viicos](https://github.com/Viicos) in [#11325](https://github.com/pydantic/pydantic/pull/11325)
|
| 777 |
+
* Fix url python serialization by [@sydney-runkle](https://github.com/sydney-runkle) in [#11331](https://github.com/pydantic/pydantic/pull/11331)
|
| 778 |
+
|
| 779 |
+
## v2.10.5 (2025-01-08)
|
| 780 |
+
|
| 781 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.5)
|
| 782 |
+
|
| 783 |
+
### What's Changed
|
| 784 |
+
|
| 785 |
+
#### Fixes
|
| 786 |
+
|
| 787 |
+
* Remove custom MRO implementation of Pydantic models by [@Viicos](https://github.com/Viicos) in [#11184](https://github.com/pydantic/pydantic/pull/11184)
|
| 788 |
+
* Fix URL serialization for unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#11233](https://github.com/pydantic/pydantic/pull/11233)
|
| 789 |
+
|
| 790 |
+
## v2.10.4 (2024-12-18)
|
| 791 |
+
|
| 792 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.4)
|
| 793 |
+
|
| 794 |
+
### What's Changed
|
| 795 |
+
|
| 796 |
+
#### Packaging
|
| 797 |
+
|
| 798 |
+
* Bump `pydantic-core` to v2.27.2 by [@davidhewitt](https://github.com/davidhewitt) in [#11138](https://github.com/pydantic/pydantic/pull/11138)
|
| 799 |
+
|
| 800 |
+
#### Fixes
|
| 801 |
+
|
| 802 |
+
* Fix for comparison of `AnyUrl` objects by [@alexprabhat99](https://github.com/alexprabhat99) in [#11082](https://github.com/pydantic/pydantic/pull/11082)
|
| 803 |
+
* Properly fetch PEP 695 type params for functions, do not fetch annotations from signature by [@Viicos](https://github.com/Viicos) in [#11093](https://github.com/pydantic/pydantic/pull/11093)
|
| 804 |
+
* Include JSON Schema input core schema in function schemas by [@Viicos](https://github.com/Viicos) in [#11085](https://github.com/pydantic/pydantic/pull/11085)
|
| 805 |
+
* Add `len` to `_BaseUrl` to avoid TypeError by [@Kharianne](https://github.com/Kharianne) in [#11111](https://github.com/pydantic/pydantic/pull/11111)
|
| 806 |
+
* Make sure the type reference is removed from the seen references by [@Viicos](https://github.com/Viicos) in [#11143](https://github.com/pydantic/pydantic/pull/11143)
|
| 807 |
+
|
| 808 |
+
### New Contributors
|
| 809 |
+
|
| 810 |
+
* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789)
|
| 811 |
+
* [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948)
|
| 812 |
+
* [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077)
|
| 813 |
+
* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082)
|
| 814 |
+
* [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111)
|
| 815 |
+
|
| 816 |
+
## v2.10.3 (2024-12-03)
|
| 817 |
+
|
| 818 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.3)
|
| 819 |
+
|
| 820 |
+
### What's Changed
|
| 821 |
+
|
| 822 |
+
#### Fixes
|
| 823 |
+
|
| 824 |
+
* Set fields when `defer_build` is set on Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10984](https://github.com/pydantic/pydantic/pull/10984)
|
| 825 |
+
* Do not resolve the JSON Schema reference for `dict` core schema keys by [@Viicos](https://github.com/Viicos) in [#10989](https://github.com/pydantic/pydantic/pull/10989)
|
| 826 |
+
* Use the globals of the function when evaluating the return type for `PlainSerializer` and `WrapSerializer` functions by [@Viicos](https://github.com/Viicos) in [#11008](https://github.com/pydantic/pydantic/pull/11008)
|
| 827 |
+
* Fix host required enforcement for urls to be compatible with v2.9 behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11027](https://github.com/pydantic/pydantic/pull/11027)
|
| 828 |
+
* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034)
|
| 829 |
+
* Fix url json schema in `serialization` mode by [@sydney-runkle](https://github.com/sydney-runkle) in [#11035](https://github.com/pydantic/pydantic/pull/11035)
|
| 830 |
+
|
| 831 |
+
## v2.10.2 (2024-11-25)
|
| 832 |
+
|
| 833 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.2)
|
| 834 |
+
|
| 835 |
+
### What's Changed
|
| 836 |
+
|
| 837 |
+
#### Fixes
|
| 838 |
+
|
| 839 |
+
* Only evaluate FieldInfo annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769)
|
| 840 |
+
* Do not evaluate annotations for private fields by [@Viicos](https://github.com/Viicos) in [#10962](https://github.com/pydantic/pydantic/pull/10962)
|
| 841 |
+
* Support serialization as any for `Secret` types and `Url` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10947](https://github.com/pydantic/pydantic/pull/10947)
|
| 842 |
+
* Fix type hint of `Field.default` to be compatible with Python 3.8 and 3.9 by [@Viicos](https://github.com/Viicos) in [#10972](https://github.com/pydantic/pydantic/pull/10972)
|
| 843 |
+
* Add hashing support for URL types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10975](https://github.com/pydantic/pydantic/pull/10975)
|
| 844 |
+
* Hide `BaseModel.__replace__` definition from type checkers by [@Viicos](https://github.com/Viicos) in [#10979](https://github.com/pydantic/pydantic/pull/10979)
|
| 845 |
+
|
| 846 |
+
## v2.10.1 (2024-11-21)
|
| 847 |
+
|
| 848 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.1)
|
| 849 |
+
|
| 850 |
+
### What's Changed
|
| 851 |
+
|
| 852 |
+
#### Packaging
|
| 853 |
+
|
| 854 |
+
* Bump `pydantic-core` version to `v2.27.1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10938](https://github.com/pydantic/pydantic/pull/10938)
|
| 855 |
+
|
| 856 |
+
#### Fixes
|
| 857 |
+
|
| 858 |
+
* Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#10893](https://github.com/pydantic/pydantic/pull/10893)
|
| 859 |
+
* Relax check for validated data in `default_factory` utils by [@sydney-runkle](https://github.com/sydney-runkle) in [#10909](https://github.com/pydantic/pydantic/pull/10909)
|
| 860 |
+
* Fix type checking issue with `model_fields` and `model_computed_fields` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10911](https://github.com/pydantic/pydantic/pull/10911)
|
| 861 |
+
* Use the parent configuration during schema generation for stdlib `dataclass`es by [@sydney-runkle](https://github.com/sydney-runkle) in [#10928](https://github.com/pydantic/pydantic/pull/10928)
|
| 862 |
+
* Use the `globals` of the function when evaluating the return type of serializers and `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10929](https://github.com/pydantic/pydantic/pull/10929)
|
| 863 |
+
* Fix URL constraint application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10922](https://github.com/pydantic/pydantic/pull/10922)
|
| 864 |
+
* Fix URL equality with different validation methods by [@sydney-runkle](https://github.com/sydney-runkle) in [#10934](https://github.com/pydantic/pydantic/pull/10934)
|
| 865 |
+
* Fix JSON schema title when specified as `''` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10936](https://github.com/pydantic/pydantic/pull/10936)
|
| 866 |
+
* Fix `python` mode serialization for `complex` inference by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic-core#1549](https://github.com/pydantic/pydantic-core/pull/1549)
|
| 867 |
+
|
| 868 |
+
### New Contributors
|
| 869 |
+
|
| 870 |
+
## v2.10.0 (2024-11-20)
|
| 871 |
+
|
| 872 |
+
The code released in v2.10.0 is practically identical to that of v2.10.0b2.
|
| 873 |
+
|
| 874 |
+
[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0)
|
| 875 |
+
|
| 876 |
+
See the [v2.10 release blog post](https://pydantic.dev/articles/pydantic-v2-10-release) for the highlights!
|
| 877 |
+
|
| 878 |
+
### What's Changed
|
| 879 |
+
|
| 880 |
+
#### Packaging
|
| 881 |
+
|
| 882 |
+
* Bump `pydantic-core` to `v2.27.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825)
|
| 883 |
+
* Replaced pdm with uv by [@frfahim](https://github.com/frfahim) in [#10727](https://github.com/pydantic/pydantic/pull/10727)
|
| 884 |
+
|
| 885 |
+
#### New Features
|
| 886 |
+
|
| 887 |
+
* Support `fractions.Fraction` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10318](https://github.com/pydantic/pydantic/pull/10318)
|
| 888 |
+
* Support `Hashable` for json validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10324](https://github.com/pydantic/pydantic/pull/10324)
|
| 889 |
+
* Add a `SocketPath` type for `linux` systems by [@theunkn0wn1](https://github.com/theunkn0wn1) in [#10378](https://github.com/pydantic/pydantic/pull/10378)
|
| 890 |
+
* Allow arbitrary refs in JSON schema `examples` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10417](https://github.com/pydantic/pydantic/pull/10417)
|
| 891 |
+
* Support `defer_build` for Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10313](https://github.com/pydantic/pydantic/pull/10313)
|
| 892 |
+
* Adding v1 / v2 incompatibility warning for nested v1 model by [@sydney-runkle](https://github.com/sydney-runkle) in [#10431](https://github.com/pydantic/pydantic/pull/10431)
|
| 893 |
+
* Add support for unpacked `TypedDict` to type hint variadic keyword arguments with `@validate_call` by [@Viicos](https://github.com/Viicos) in [#10416](https://github.com/pydantic/pydantic/pull/10416)
|
| 894 |
+
* Support compiled patterns in `protected_namespaces` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10522](https://github.com/pydantic/pydantic/pull/10522)
|
| 895 |
+
* Add support for `propertyNames` in JSON schema by [@FlorianSW](https://github.com/FlorianSW) in [#10478](https://github.com/pydantic/pydantic/pull/10478)
|
| 896 |
+
* Adding `__replace__` protocol for Python 3.13+ support by [@sydney-runkle](https://github.com/sydney-runkle) in [#10596](https://github.com/pydantic/pydantic/pull/10596)
|
| 897 |
+
* Expose public `sort` method for JSON schema generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10595](https://github.com/pydantic/pydantic/pull/10595)
|
| 898 |
+
* Add runtime validation of `@validate_call` callable argument by [@kc0506](https://github.com/kc0506) in [#10627](https://github.com/pydantic/pydantic/pull/10627)
|
| 899 |
+
* Add `experimental_allow_partial` support by [@samuelcolvin](https://github.com/samuelcolvin) in [#10748](https://github.com/pydantic/pydantic/pull/10748)
|
| 900 |
+
* Support default factories taking validated data as an argument by [@Viicos](https://github.com/Viicos) in [#10678](https://github.com/pydantic/pydantic/pull/10678)
|
| 901 |
+
* Allow subclassing `ValidationError` and `PydanticCustomError` by [@Youssefares](https://github.com/Youssefares) in [pydantic/pydantic-core#1413](https://github.com/pydantic/pydantic-core/pull/1413)
|
| 902 |
+
* Add `trailing-strings` support to `experimental_allow_partial` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825)
|
| 903 |
+
* Add `rebuild()` method for `TypeAdapter` and simplify `defer_build` patterns by [@sydney-runkle](https://github.com/sydney-runkle) in [#10537](https://github.com/pydantic/pydantic/pull/10537)
|
| 904 |
+
* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872)
|
| 905 |
+
|
| 906 |
+
#### Changes
|
| 907 |
+
|
| 908 |
+
* Don't allow customization of `SchemaGenerator` until interface is more stable by [@sydney-runkle](https://github.com/sydney-runkle) in [#10303](https://github.com/pydantic/pydantic/pull/10303)
|
| 909 |
+
* Cleanly `defer_build` on `TypeAdapters`, removing experimental flag by [@sydney-runkle](https://github.com/sydney-runkle) in [#10329](https://github.com/pydantic/pydantic/pull/10329)
|
| 910 |
+
* Fix `mro` of generic subclass by [@kc0506](https://github.com/kc0506) in [#10100](https://github.com/pydantic/pydantic/pull/10100)
|
| 911 |
+
* Strip whitespaces on JSON Schema title generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10404](https://github.com/pydantic/pydantic/pull/10404)
|
| 912 |
+
* Use `b64decode` and `b64encode` for `Base64Bytes` type by [@sydney-runkle](https://github.com/sydney-runkle) in [#10486](https://github.com/pydantic/pydantic/pull/10486)
|
| 913 |
+
* Relax protected namespace config default by [@sydney-runkle](https://github.com/sydney-runkle) in [#10441](https://github.com/pydantic/pydantic/pull/10441)
|
| 914 |
+
* Revalidate parametrized generics if instance's origin is subclass of OG class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10666](https://github.com/pydantic/pydantic/pull/10666)
|
| 915 |
+
* Warn if configuration is specified on the `@dataclass` decorator and with the `__pydantic_config__` attribute by [@sydney-runkle](https://github.com/sydney-runkle) in [#10406](https://github.com/pydantic/pydantic/pull/10406)
|
| 916 |
+
* Recommend against using `Ellipsis` (...) with `Field` by [@Viicos](https://github.com/Viicos) in [#10661](https://github.com/pydantic/pydantic/pull/10661)
|
| 917 |
+
* Migrate to subclassing instead of annotated approach for pydantic url types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10662](https://github.com/pydantic/pydantic/pull/10662)
|
| 918 |
+
* Change JSON schema generation of `Literal`s and `Enums` by [@Viicos](https://github.com/Viicos) in [#10692](https://github.com/pydantic/pydantic/pull/10692)
|
| 919 |
+
* Simplify unions involving `Any` or `Never` when replacing type variables by [@Viicos](https://github.com/Viicos) in [#10338](https://github.com/pydantic/pydantic/pull/10338)
|
| 920 |
+
* Do not require padding when decoding `base64` bytes by [@bschoenmaeckers](https://github.com/bschoenmaeckers) in [pydantic/pydantic-core#1448](https://github.com/pydantic/pydantic-core/pull/1448)
|
| 921 |
+
* Support dates all the way to 1BC by [@changhc](https://github.com/changhc) in [pydantic/speedate#77](https://github.com/pydantic/speedate/pull/77)
|
| 922 |
+
|
| 923 |
+
#### Performance
|
| 924 |
+
|
| 925 |
+
* Schema cleaning: skip unnecessary copies during schema walking by [@Viicos](https://github.com/Viicos) in [#10286](https://github.com/pydantic/pydantic/pull/10286)
|
| 926 |
+
* Refactor namespace logic for annotations evaluation by [@Viicos](https://github.com/Viicos) in [#10530](https://github.com/pydantic/pydantic/pull/10530)
|
| 927 |
+
* Improve email regexp on edge cases by [@AlekseyLobanov](https://github.com/AlekseyLobanov) in [#10601](https://github.com/pydantic/pydantic/pull/10601)
|
| 928 |
+
* `CoreMetadata` refactor with an emphasis on documentation, schema build time performance, and reducing complexity by [@sydney-runkle](https://github.com/sydney-runkle) in [#10675](https://github.com/pydantic/pydantic/pull/10675)
|
| 929 |
+
|
| 930 |
+
#### Fixes
|
| 931 |
+
|
| 932 |
+
* Remove guarding check on `computed_field` with `field_serializer` by [@nix010](https://github.com/nix010) in [#10390](https://github.com/pydantic/pydantic/pull/10390)
|
| 933 |
+
* Fix `Predicate` issue in `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10321](https://github.com/pydantic/pydantic/pull/10321)
|
| 934 |
+
* Fixing `annotated-types` bound by [@sydney-runkle](https://github.com/sydney-runkle) in [#10327](https://github.com/pydantic/pydantic/pull/10327)
|
| 935 |
+
* Turn `tzdata` install requirement into optional `timezone` dependency by [@jakob-keller](https://github.com/jakob-keller) in [#10331](https://github.com/pydantic/pydantic/pull/10331)
|
| 936 |
+
* Use correct types namespace when building `namedtuple` core schemas by [@Viicos](https://github.com/Viicos) in [#10337](https://github.com/pydantic/pydantic/pull/10337)
|
| 937 |
+
* Fix evaluation of stringified annotations during namespace inspection by [@Viicos](https://github.com/Viicos) in [#10347](https://github.com/pydantic/pydantic/pull/10347)
|
| 938 |
+
* Fix `IncEx` type alias definition by [@Viicos](https://github.com/Viicos) in [#10339](https://github.com/pydantic/pydantic/pull/10339)
|
| 939 |
+
* Do not error when trying to evaluate annotations of private attributes by [@Viicos](https://github.com/Viicos) in [#10358](https://github.com/pydantic/pydantic/pull/10358)
|
| 940 |
+
* Fix nested type statement by [@kc0506](https://github.com/kc0506) in [#10369](https://github.com/pydantic/pydantic/pull/10369)
|
| 941 |
+
* Improve typing of `ModelMetaclass.mro` by [@Viicos](https://github.com/Viicos) in [#10372](https://github.com/pydantic/pydantic/pull/10372)
|
| 942 |
+
* Fix class access of deprecated `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10391](https://github.com/pydantic/pydantic/pull/10391)
|
| 943 |
+
* Make sure `inspect.iscoroutinefunction` works on coroutines decorated with `@validate_call` by [@MovisLi](https://github.com/MovisLi) in [#10374](https://github.com/pydantic/pydantic/pull/10374)
|
| 944 |
+
* Fix `NameError` when using `validate_call` with PEP 695 on a class by [@kc0506](https://github.com/kc0506) in [#10380](https://github.com/pydantic/pydantic/pull/10380)
|
| 945 |
+
* Fix `ZoneInfo` with various invalid types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10408](https://github.com/pydantic/pydantic/pull/10408)
|
| 946 |
+
* Fix `PydanticUserError` on empty `model_config` with annotations by [@cdwilson](https://github.com/cdwilson) in [#10412](https://github.com/pydantic/pydantic/pull/10412)
|
| 947 |
+
* Fix variance issue in `_IncEx` type alias, only allow `True` by [@Viicos](https://github.com/Viicos) in [#10414](https://github.com/pydantic/pydantic/pull/10414)
|
| 948 |
+
* Fix serialization schema generation when using `PlainValidator` by [@Viicos](https://github.com/Viicos) in [#10427](https://github.com/pydantic/pydantic/pull/10427)
|
| 949 |
+
* Fix schema generation error when serialization schema holds references by [@Viicos](https://github.com/Viicos) in [#10444](https://github.com/pydantic/pydantic/pull/10444)
|
| 950 |
+
* Inline references if possible when generating schema for `json_schema_input_type` by [@Viicos](https://github.com/Viicos) in [#10439](https://github.com/pydantic/pydantic/pull/10439)
|
| 951 |
+
* Fix recursive arguments in `Representation` by [@Viicos](https://github.com/Viicos) in [#10480](https://github.com/pydantic/pydantic/pull/10480)
|
| 952 |
+
* Fix representation for builtin function types by [@kschwab](https://github.com/kschwab) in [#10479](https://github.com/pydantic/pydantic/pull/10479)
|
| 953 |
+
* Add python validators for decimal constraints (`max_digits` and `decimal_places`) by [@sydney-runkle](https://github.com/sydney-runkle) in [#10506](https://github.com/pydantic/pydantic/pull/10506)
|
| 954 |
+
* Only fetch `__pydantic_core_schema__` from the current class during schema generation by [@Viicos](https://github.com/Viicos) in [#10518](https://github.com/pydantic/pydantic/pull/10518)
|
| 955 |
+
* Fix `stacklevel` on deprecation warnings for `BaseModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10520](https://github.com/pydantic/pydantic/pull/10520)
|
| 956 |
+
* Fix warning `stacklevel` in `BaseModel.__init__` by [@Viicos](https://github.com/Viicos) in [#10526](https://github.com/pydantic/pydantic/pull/10526)
|
| 957 |
+
* Improve error handling for in-evaluable refs for discriminator application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10440](https://github.com/pydantic/pydantic/pull/10440)
|
| 958 |
+
* Change the signature of `ConfigWrapper.core_config` to take the title directly by [@Viicos](https://github.com/Viicos) in [#10562](https://github.com/pydantic/pydantic/pull/10562)
|
| 959 |
+
* Do not use the previous config from the stack for dataclasses without config by [@Viicos](https://github.com/Viicos) in [#10576](https://github.com/pydantic/pydantic/pull/10576)
|
| 960 |
+
* Fix serialization for IP types with `mode='python'` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10594](https://github.com/pydantic/pydantic/pull/10594)
|
| 961 |
+
* Support constraint application for `Base64Etc` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10584](https://github.com/pydantic/pydantic/pull/10584)
|
| 962 |
+
* Fix `validate_call` ignoring `Field` in `Annotated` by [@kc0506](https://github.com/kc0506) in [#10610](https://github.com/pydantic/pydantic/pull/10610)
|
| 963 |
+
* Raise an error when `Self` is invalid by [@kc0506](https://github.com/kc0506) in [#10609](https://github.com/pydantic/pydantic/pull/10609)
|
| 964 |
+
* Using `core_schema.InvalidSchema` instead of metadata injection + checks by [@sydney-runkle](https://github.com/sydney-runkle) in [#10523](https://github.com/pydantic/pydantic/pull/10523)
|
| 965 |
+
* Tweak type alias logic by [@kc0506](https://github.com/kc0506) in [#10643](https://github.com/pydantic/pydantic/pull/10643)
|
| 966 |
+
* Support usage of `type` with `typing.Self` and type aliases by [@kc0506](https://github.com/kc0506) in [#10621](https://github.com/pydantic/pydantic/pull/10621)
|
| 967 |
+
* Use overloads for `Field` and `PrivateAttr` functions by [@Viicos](https://github.com/Viicos) in [#10651](https://github.com/pydantic/pydantic/pull/10651)
|
| 968 |
+
* Clean up the `mypy` plugin implementation by [@Viicos](https://github.com/Viicos) in [#10669](https://github.com/pydantic/pydantic/pull/10669)
|
| 969 |
+
* Properly check for `typing_extensions` variant of `TypeAliasType` by [@Daraan](https://github.com/Daraan) in [#10713](https://github.com/pydantic/pydantic/pull/10713)
|
| 970 |
+
* Allow any mapping in `BaseModel.model_copy()` by [@Viicos](https://github.com/Viicos) in [#10751](https://github.com/pydantic/pydantic/pull/10751)
|
| 971 |
+
* Fix `isinstance` behavior for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10766](https://github.com/pydantic/pydantic/pull/10766)
|
| 972 |
+
* Ensure `cached_property` can be set on Pydantic models by [@Viicos](https://github.com/Viicos) in [#10774](https://github.com/pydantic/pydantic/pull/10774)
|
| 973 |
+
* Fix equality checks for primitives in literals by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1459](https://github.com/pydantic/pydantic-core/pull/1459)
|
| 974 |
+
* Properly enforce `host_required` for URLs by [@Viicos](https://github.com/Viicos) in [pydantic/pydantic-core#1488](https://github.com/pydantic/pydantic-core/pull/1488)
|
| 975 |
+
* Fix when `coerce_numbers_to_str` enabled and string has invalid Unicode character by [@andrey-berenda](https://github.com/andrey-berenda) in [pydantic/pydantic-core#1515](https://github.com/pydantic/pydantic-core/pull/1515)
|
| 976 |
+
* Fix serializing `complex` values in `Enum`s by [@changhc](https://github.com/changhc) in [pydantic/pydantic-core#1524](https://github.com/pydantic/pydantic-core/pull/1524)
|
| 977 |
+
* Refactor `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#10725](https://github.com/pydantic/pydantic/pull/10725)
|
| 978 |
+
* Support intuitive equality for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10798](https://github.com/pydantic/pydantic/pull/10798)
|
| 979 |
+
* Add `bytearray` to `TypeAdapter.validate_json` signature by [@samuelcolvin](https://github.com/samuelcolvin) in [#10802](https://github.com/pydantic/pydantic/pull/10802)
|
| 980 |
+
* Ensure class access of method descriptors is performed when used as a default with `Field` by [@Viicos](https://github.com/Viicos) in [#10816](https://github.com/pydantic/pydantic/pull/10816)
|
| 981 |
+
* Fix circular import with `validate_call` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10807](https://github.com/pydantic/pydantic/pull/10807)
|
| 982 |
+
* Fix error when using type aliases referencing other type aliases by [@Viicos](https://github.com/Viicos) in [#10809](https://github.com/pydantic/pydantic/pull/10809)
|
| 983 |
+
* Fix `IncEx` type alias to be compatible with mypy by [@Viicos](https://github.com/Viicos) in [#10813](https://github.com/pydantic/pydantic/pull/10813)
|
| 984 |
+
* Make `__signature__` a lazy property, do not deepcopy defaults by [@Viicos](https://github.com/Viicos) in [#10818](https://github.com/pydantic/pydantic/pull/10818)
|
| 985 |
+
* Make `__signature__` lazy for dataclasses, too by [@sydney-runkle](https://github.com/sydney-runkle) in [#10832](https://github.com/pydantic/pydantic/pull/10832)
|
| 986 |
+
* Subclass all single host url classes from `AnyUrl` to preserve behavior from v2.9 by [@sydney-runkle](https://github.com/sydney-runkle) in [#10856](https://github.com/pydantic/pydantic/pull/10856)
|
| 987 |
+
|
| 988 |
+
### New Contributors
|
| 989 |
+
|
| 990 |
+
* [@jakob-keller](https://github.com/jakob-keller) made their first contribution in [#10331](https://github.com/pydantic/pydantic/pull/10331)
|
| 991 |
+
* [@MovisLi](https://github.com/MovisLi) made their first contribution in [#10374](https://github.com/pydantic/pydantic/pull/10374)
|
| 992 |
+
* [@joaopalmeiro](https://github.com/joaopalmeiro) made their first contribution in [#10405](https://github.com/pydantic/pydantic/pull/10405)
|
| 993 |
+
* [@theunkn0wn1](https://github.com/theunkn0wn1) made their first contribution in [#10378](https://github.com/pydantic/pydantic/pull/10378)
|
| 994 |
+
* [@cdwilson](https://github.com/cdwilson) made their first contribution in [#10412](https://github.com/pydantic/pydantic/pull/10412)
|
| 995 |
+
* [@dlax](https://github.com/dlax) made their first contribution in [#10421](https://github.com/pydantic/pydantic/pull/10421)
|
| 996 |
+
* [@kschwab](https://github.com/kschwab) made their first contribution in [#10479](https://github.com/pydantic/pydantic/pull/10479)
|
| 997 |
+
* [@santibreo](https://github.com/santibreo) made their first contribution in [#10453](https://github.com/pydantic/pydantic/pull/10453)
|
| 998 |
+
* [@FlorianSW](https://github.com/FlorianSW) made their first contribution in [#10478](https://github.com/pydantic/pydantic/pull/10478)
|
| 999 |
+
* [@tkasuz](https://github.com/tkasuz) made their first contribution in [#10555](https://github.com/pydantic/pydantic/pull/10555)
|
| 1000 |
+
* [@AlekseyLobanov](https://github.com/AlekseyLobanov) made their first contribution in [#10601](https://github.com/pydantic/pydantic/pull/10601)
|
| 1001 |
+
* [@NiclasvanEyk](https://github.com/NiclasvanEyk) made their first contribution in [#10667](https://github.com/pydantic/pydantic/pull/10667)
|
| 1002 |
+
* [@mschoettle](https://github.com/mschoettle) made their first contribution in [#10677](https://github.com/pydantic/pydantic/pull/10677)
|
| 1003 |
+
* [@Daraan](https://github.com/Daraan) made their first contribution in [#10713](https://github.com/pydantic/pydantic/pull/10713)
|
| 1004 |
+
* [@k4nar](https://github.com/k4nar) made their first contribution in [#10736](https://github.com/pydantic/pydantic/pull/10736)
|
| 1005 |
+
* [@UriyaHarpeness](https://github.com/UriyaHarpeness) made their first contribution in [#10740](https://github.com/pydantic/pydantic/pull/10740)
|
| 1006 |
+
* [@frfahim](https://github.com/frfahim) made their first contribution in [#10727](https://github.com/pydantic/pydantic/pull/10727)
|
| 1007 |
+
|
| 1008 |
+
## v2.10.0b2 (2024-11-13)
|
| 1009 |
+
|
| 1010 |
+
Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b2) for details.
|
| 1011 |
+
|
| 1012 |
+
## v2.10.0b1 (2024-11-06)
|
| 1013 |
+
|
| 1014 |
+
Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b1) for details.
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
... see [here](https://docs.pydantic.dev/changelog/#v0322-2019-08-17) for earlier changes.
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/RECORD
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
pydantic-2.12.4.dist-info/METADATA,sha256=n-oEZ-oPi9CLD6_06tpdKVIAf6HjvpsB6oaOYOo88lQ,89859
|
| 3 |
+
pydantic-2.12.4.dist-info/RECORD,,
|
| 4 |
+
pydantic-2.12.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
pydantic-2.12.4.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
| 6 |
+
pydantic-2.12.4.dist-info/direct_url.json,sha256=1rwprGxuZEqnWqIcYV0LelY9F2pCg3s8uEHb2fLaAzE,98
|
| 7 |
+
pydantic-2.12.4.dist-info/licenses/LICENSE,sha256=qeGG88oWte74QxjnpwFyE1GgDLe4rjpDlLZ7SeNSnvM,1129
|
| 8 |
+
pydantic/__init__.py,sha256=5iEnJ4wHv1OEzdKQPzaKaZKfO4pSQAC65ODrYI6_S8Y,15812
|
| 9 |
+
pydantic/__pycache__/__init__.cpython-313.pyc,,
|
| 10 |
+
pydantic/__pycache__/_migration.cpython-313.pyc,,
|
| 11 |
+
pydantic/__pycache__/alias_generators.cpython-313.pyc,,
|
| 12 |
+
pydantic/__pycache__/aliases.cpython-313.pyc,,
|
| 13 |
+
pydantic/__pycache__/annotated_handlers.cpython-313.pyc,,
|
| 14 |
+
pydantic/__pycache__/class_validators.cpython-313.pyc,,
|
| 15 |
+
pydantic/__pycache__/color.cpython-313.pyc,,
|
| 16 |
+
pydantic/__pycache__/config.cpython-313.pyc,,
|
| 17 |
+
pydantic/__pycache__/dataclasses.cpython-313.pyc,,
|
| 18 |
+
pydantic/__pycache__/datetime_parse.cpython-313.pyc,,
|
| 19 |
+
pydantic/__pycache__/decorator.cpython-313.pyc,,
|
| 20 |
+
pydantic/__pycache__/env_settings.cpython-313.pyc,,
|
| 21 |
+
pydantic/__pycache__/error_wrappers.cpython-313.pyc,,
|
| 22 |
+
pydantic/__pycache__/errors.cpython-313.pyc,,
|
| 23 |
+
pydantic/__pycache__/fields.cpython-313.pyc,,
|
| 24 |
+
pydantic/__pycache__/functional_serializers.cpython-313.pyc,,
|
| 25 |
+
pydantic/__pycache__/functional_validators.cpython-313.pyc,,
|
| 26 |
+
pydantic/__pycache__/generics.cpython-313.pyc,,
|
| 27 |
+
pydantic/__pycache__/json.cpython-313.pyc,,
|
| 28 |
+
pydantic/__pycache__/json_schema.cpython-313.pyc,,
|
| 29 |
+
pydantic/__pycache__/main.cpython-313.pyc,,
|
| 30 |
+
pydantic/__pycache__/mypy.cpython-313.pyc,,
|
| 31 |
+
pydantic/__pycache__/networks.cpython-313.pyc,,
|
| 32 |
+
pydantic/__pycache__/parse.cpython-313.pyc,,
|
| 33 |
+
pydantic/__pycache__/root_model.cpython-313.pyc,,
|
| 34 |
+
pydantic/__pycache__/schema.cpython-313.pyc,,
|
| 35 |
+
pydantic/__pycache__/tools.cpython-313.pyc,,
|
| 36 |
+
pydantic/__pycache__/type_adapter.cpython-313.pyc,,
|
| 37 |
+
pydantic/__pycache__/types.cpython-313.pyc,,
|
| 38 |
+
pydantic/__pycache__/typing.cpython-313.pyc,,
|
| 39 |
+
pydantic/__pycache__/utils.cpython-313.pyc,,
|
| 40 |
+
pydantic/__pycache__/validate_call_decorator.cpython-313.pyc,,
|
| 41 |
+
pydantic/__pycache__/validators.cpython-313.pyc,,
|
| 42 |
+
pydantic/__pycache__/version.cpython-313.pyc,,
|
| 43 |
+
pydantic/__pycache__/warnings.cpython-313.pyc,,
|
| 44 |
+
pydantic/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 45 |
+
pydantic/_internal/__pycache__/__init__.cpython-313.pyc,,
|
| 46 |
+
pydantic/_internal/__pycache__/_config.cpython-313.pyc,,
|
| 47 |
+
pydantic/_internal/__pycache__/_core_metadata.cpython-313.pyc,,
|
| 48 |
+
pydantic/_internal/__pycache__/_core_utils.cpython-313.pyc,,
|
| 49 |
+
pydantic/_internal/__pycache__/_dataclasses.cpython-313.pyc,,
|
| 50 |
+
pydantic/_internal/__pycache__/_decorators.cpython-313.pyc,,
|
| 51 |
+
pydantic/_internal/__pycache__/_decorators_v1.cpython-313.pyc,,
|
| 52 |
+
pydantic/_internal/__pycache__/_discriminated_union.cpython-313.pyc,,
|
| 53 |
+
pydantic/_internal/__pycache__/_docs_extraction.cpython-313.pyc,,
|
| 54 |
+
pydantic/_internal/__pycache__/_fields.cpython-313.pyc,,
|
| 55 |
+
pydantic/_internal/__pycache__/_forward_ref.cpython-313.pyc,,
|
| 56 |
+
pydantic/_internal/__pycache__/_generate_schema.cpython-313.pyc,,
|
| 57 |
+
pydantic/_internal/__pycache__/_generics.cpython-313.pyc,,
|
| 58 |
+
pydantic/_internal/__pycache__/_git.cpython-313.pyc,,
|
| 59 |
+
pydantic/_internal/__pycache__/_import_utils.cpython-313.pyc,,
|
| 60 |
+
pydantic/_internal/__pycache__/_internal_dataclass.cpython-313.pyc,,
|
| 61 |
+
pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-313.pyc,,
|
| 62 |
+
pydantic/_internal/__pycache__/_mock_val_ser.cpython-313.pyc,,
|
| 63 |
+
pydantic/_internal/__pycache__/_model_construction.cpython-313.pyc,,
|
| 64 |
+
pydantic/_internal/__pycache__/_namespace_utils.cpython-313.pyc,,
|
| 65 |
+
pydantic/_internal/__pycache__/_repr.cpython-313.pyc,,
|
| 66 |
+
pydantic/_internal/__pycache__/_schema_gather.cpython-313.pyc,,
|
| 67 |
+
pydantic/_internal/__pycache__/_schema_generation_shared.cpython-313.pyc,,
|
| 68 |
+
pydantic/_internal/__pycache__/_serializers.cpython-313.pyc,,
|
| 69 |
+
pydantic/_internal/__pycache__/_signature.cpython-313.pyc,,
|
| 70 |
+
pydantic/_internal/__pycache__/_typing_extra.cpython-313.pyc,,
|
| 71 |
+
pydantic/_internal/__pycache__/_utils.cpython-313.pyc,,
|
| 72 |
+
pydantic/_internal/__pycache__/_validate_call.cpython-313.pyc,,
|
| 73 |
+
pydantic/_internal/__pycache__/_validators.cpython-313.pyc,,
|
| 74 |
+
pydantic/_internal/_config.py,sha256=TWZwg3c0bZHiT3boR5-YYqkouHcwjRdenmyGHofV7E0,14674
|
| 75 |
+
pydantic/_internal/_core_metadata.py,sha256=Y_g2t3i7uluK-wXCZvzJfRFMPUM23aBYLfae4FzBPy0,5162
|
| 76 |
+
pydantic/_internal/_core_utils.py,sha256=1jru4VbJ0x63R6dtVcuOI-dKQTC_d_lSnJWEBQzGNEQ,6487
|
| 77 |
+
pydantic/_internal/_dataclasses.py,sha256=Tk1mEafhad1kV7K5tPX5BwxWSXY7C-MKwf0OLFgIlEA,13158
|
| 78 |
+
pydantic/_internal/_decorators.py,sha256=PnyAoKSg3BNbCVSZnwqw9naEg1UDtYvDT9LluigPiO8,33529
|
| 79 |
+
pydantic/_internal/_decorators_v1.py,sha256=tfdfdpQKY4R2XCOwqHbZeoQMur6VNigRrfhudXBHx38,6185
|
| 80 |
+
pydantic/_internal/_discriminated_union.py,sha256=aMl0SRSyQyHfW4-klnMTHNvwSRoqE3H3PRV_05vRsTg,25478
|
| 81 |
+
pydantic/_internal/_docs_extraction.py,sha256=fyznSAHh5AzohnXZStV0HvH-nRbavNHPyg-knx-S_EE,4127
|
| 82 |
+
pydantic/_internal/_fields.py,sha256=YSfEKq21FgjLJ6YqYXKh0eEEs5nxMPvQ6hp9pA8Nzfw,28093
|
| 83 |
+
pydantic/_internal/_forward_ref.py,sha256=5n3Y7-3AKLn8_FS3Yc7KutLiPUhyXmAtkEZOaFnonwM,611
|
| 84 |
+
pydantic/_internal/_generate_schema.py,sha256=TT49vzYzqH90rWrv5ptNoZgjzOsR0KPlSkqPVFrnrBw,132665
|
| 85 |
+
pydantic/_internal/_generics.py,sha256=ELqjT6LMzQzWAK0EB5_9qke_iAazz0OQ4gunp_uKuYY,23822
|
| 86 |
+
pydantic/_internal/_git.py,sha256=IwPh3DPfa2Xq3rBuB9Nx8luR2A1i69QdeTfWWXIuCVg,809
|
| 87 |
+
pydantic/_internal/_import_utils.py,sha256=TRhxD5OuY6CUosioBdBcJUs0om7IIONiZdYAV7zQ8jM,402
|
| 88 |
+
pydantic/_internal/_internal_dataclass.py,sha256=_bedc1XbuuygRGiLZqkUkwwFpQaoR1hKLlR501nyySY,144
|
| 89 |
+
pydantic/_internal/_known_annotated_metadata.py,sha256=Jc7KTNFZoB3f-0ibP_NgJINOeVvYE3q3OTBQDjVMk3U,16765
|
| 90 |
+
pydantic/_internal/_mock_val_ser.py,sha256=wmRRFSBvqfcLbI41PsFliB4u2AZ3mJpZeiERbD3xKTo,8885
|
| 91 |
+
pydantic/_internal/_model_construction.py,sha256=wk-bNGDAJvduaGvn0U0_8zEl0GERu0shJvN8_ZfkYaw,37783
|
| 92 |
+
pydantic/_internal/_namespace_utils.py,sha256=hl3-TRAr82U2jTyPP3t-QqsvKLirxtkLfNfrN-fp0x8,12878
|
| 93 |
+
pydantic/_internal/_repr.py,sha256=jQfnJuyDxQpSRNhG29II9PX8e4Nv2qWZrEw2lqih3UE,5172
|
| 94 |
+
pydantic/_internal/_schema_gather.py,sha256=VLEv51TYEeeND2czsyrmJq1MVnJqTOmnLan7VG44c8A,9114
|
| 95 |
+
pydantic/_internal/_schema_generation_shared.py,sha256=F_rbQbrkoomgxsskdHpP0jUJ7TCfe0BADAEkq6CJ4nM,4842
|
| 96 |
+
pydantic/_internal/_serializers.py,sha256=YIWvSmAR5fnbGSWCOQduWt1yB4ZQY42eAruc-enrb6c,1491
|
| 97 |
+
pydantic/_internal/_signature.py,sha256=8EljPJe4pSnapuirG5DkBAgD1hggHxEAyzFPH-9H0zE,6779
|
| 98 |
+
pydantic/_internal/_typing_extra.py,sha256=_GRYopNi4a9USi5UQ285ObrlsYmvqKEWTNbBoJFSK2c,30309
|
| 99 |
+
pydantic/_internal/_utils.py,sha256=CHjH-0znUjX9R5sUSjPT8j8--7Pze8yjaiescTAVLiQ,15799
|
| 100 |
+
pydantic/_internal/_validate_call.py,sha256=PfdVnSzhXOrENtaDoDw3PFWPVYD5W_gNYPe8p3Ug6Lg,5321
|
| 101 |
+
pydantic/_internal/_validators.py,sha256=dv0a2Nkc4zcYqv31Gh_QId2lcf-W0kQpV0oSNzgEdfg,20588
|
| 102 |
+
pydantic/_migration.py,sha256=VF73LRCUz3Irb5xVt13jb3NAcXVnEF6T1-J0OLfeZ5A,12160
|
| 103 |
+
pydantic/alias_generators.py,sha256=KM1n3u4JfLSBl1UuYg3hoYHzXJD-yvgrnq8u1ccwh_A,2124
|
| 104 |
+
pydantic/aliases.py,sha256=vhCHyoSWnX-EJ-wWb5qj4xyRssgGWnTQfzQp4GSZ9ug,4937
|
| 105 |
+
pydantic/annotated_handlers.py,sha256=WfyFSqwoEIFXBh7T73PycKloI1DiX45GWi0-JOsCR4Y,4407
|
| 106 |
+
pydantic/class_validators.py,sha256=i_V3j-PYdGLSLmj_IJZekTRjunO8SIVz8LMlquPyP7E,148
|
| 107 |
+
pydantic/color.py,sha256=AzqGfVQHF92_ZctDcue0DM4yTp2P6tekkwRINTWrLIo,21481
|
| 108 |
+
pydantic/config.py,sha256=uDZ2xN-J7CVQNenCaVKcYsJEzIOpKqlgfQvDd001wik,45181
|
| 109 |
+
pydantic/dataclasses.py,sha256=2_jN-51ZWruyIsenjLI1-Vhd4qIGNF3eue9jGcdpqHI,18856
|
| 110 |
+
pydantic/datetime_parse.py,sha256=QC-WgMxMr_wQ_mNXUS7AVf-2hLEhvvsPY1PQyhSGOdk,150
|
| 111 |
+
pydantic/decorator.py,sha256=YX-jUApu5AKaVWKPoaV-n-4l7UbS69GEt9Ra3hszmKI,145
|
| 112 |
+
pydantic/deprecated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 113 |
+
pydantic/deprecated/__pycache__/__init__.cpython-313.pyc,,
|
| 114 |
+
pydantic/deprecated/__pycache__/class_validators.cpython-313.pyc,,
|
| 115 |
+
pydantic/deprecated/__pycache__/config.cpython-313.pyc,,
|
| 116 |
+
pydantic/deprecated/__pycache__/copy_internals.cpython-313.pyc,,
|
| 117 |
+
pydantic/deprecated/__pycache__/decorator.cpython-313.pyc,,
|
| 118 |
+
pydantic/deprecated/__pycache__/json.cpython-313.pyc,,
|
| 119 |
+
pydantic/deprecated/__pycache__/parse.cpython-313.pyc,,
|
| 120 |
+
pydantic/deprecated/__pycache__/tools.cpython-313.pyc,,
|
| 121 |
+
pydantic/deprecated/class_validators.py,sha256=EAcaVQM5zp2wBml0ybN62CfQfyJvDLx5Qd9Pk4_tb4U,10273
|
| 122 |
+
pydantic/deprecated/config.py,sha256=k_lsVk57paxLJOcBueH07cu1OgEgWdVBxm6lfaC3CCU,2663
|
| 123 |
+
pydantic/deprecated/copy_internals.py,sha256=Ghd-vkMd5EYCCgyCGtPKO58np9cEKBQC6qkBeIEFI2g,7618
|
| 124 |
+
pydantic/deprecated/decorator.py,sha256=TBm6bJ7wJsNih_8Wq5IzDcwP32m9_vfxs96desLuk00,10845
|
| 125 |
+
pydantic/deprecated/json.py,sha256=HlWCG35RRrxyzuTS6LTQiZBwRhmDZWmeqQH8rLW6wA8,4657
|
| 126 |
+
pydantic/deprecated/parse.py,sha256=Gzd6b_g8zJXcuE7QRq5adhx_EMJahXfcpXCF0RgrqqI,2511
|
| 127 |
+
pydantic/deprecated/tools.py,sha256=Nrm9oFRZWp8-jlfvPgJILEsywp4YzZD52XIGPDLxHcI,3330
|
| 128 |
+
pydantic/env_settings.py,sha256=6IHeeWEqlUPRUv3V-AXiF_W91fg2Jw_M3O0l34J_eyA,148
|
| 129 |
+
pydantic/error_wrappers.py,sha256=RK6mqATc9yMD-KBD9IJS9HpKCprWHd8wo84Bnm-3fR8,150
|
| 130 |
+
pydantic/errors.py,sha256=7ctBNCtt57kZFx71Ls2H86IufQARv4wPKf8DhdsVn5w,6002
|
| 131 |
+
pydantic/experimental/__init__.py,sha256=QT7rKYdDsCiTJ9GEjmsQdWHScwpKrrNkGq6vqONP6RQ,104
|
| 132 |
+
pydantic/experimental/__pycache__/__init__.cpython-313.pyc,,
|
| 133 |
+
pydantic/experimental/__pycache__/arguments_schema.cpython-313.pyc,,
|
| 134 |
+
pydantic/experimental/__pycache__/missing_sentinel.cpython-313.pyc,,
|
| 135 |
+
pydantic/experimental/__pycache__/pipeline.cpython-313.pyc,,
|
| 136 |
+
pydantic/experimental/arguments_schema.py,sha256=EFnjX_ulp-tPyUjQX5pmQtug1OFL_Acc8bcMbLd-fVY,1866
|
| 137 |
+
pydantic/experimental/missing_sentinel.py,sha256=hQejgtF00wUuQMni9429evg-eXyIwpKvjsD8ofqfj-w,127
|
| 138 |
+
pydantic/experimental/pipeline.py,sha256=Kv_dvcexKumazfRL0y69AayeA6H37SrmsZ3SUl_n0qY,23582
|
| 139 |
+
pydantic/fields.py,sha256=WuDGOvB22KWuuW3fXnS4Wvg4qX_tdp8X7BrAlza4sw8,79194
|
| 140 |
+
pydantic/functional_serializers.py,sha256=rEzH391zqy3o_bWk2QEuvySmcQNZmwXmJQLC3ZGF7QA,17151
|
| 141 |
+
pydantic/functional_validators.py,sha256=c_-7weWpGNcOYfRfVUFu11jrxMVMdfY_c-4istwk95Y,31839
|
| 142 |
+
pydantic/generics.py,sha256=0ZqZ9O9annIj_3mGBRqps4htey3b5lV1-d2tUxPMMnA,144
|
| 143 |
+
pydantic/json.py,sha256=ZH8RkI7h4Bz-zp8OdTAxbJUoVvcoU-jhMdRZ0B-k0xc,140
|
| 144 |
+
pydantic/json_schema.py,sha256=-h8c7vsNGAJCIxR-n52-69Q54w38EM-j0AGC_4VGt30,123653
|
| 145 |
+
pydantic/main.py,sha256=77QUwTtQQdUafor3ir5w2CC1s0vigFtGB0fSlTvF27I,83899
|
| 146 |
+
pydantic/mypy.py,sha256=p6KU1GwPHazF7E5vJq1uLd4tHd6DE6bre4-m5Ln23ms,58986
|
| 147 |
+
pydantic/networks.py,sha256=Smf_RyImQ-F5FZLCgFwHPfROYxW_e-Hz68R_8LW0sZ0,42099
|
| 148 |
+
pydantic/parse.py,sha256=wkd82dgtvWtD895U_I6E1htqMlGhBSYEV39cuBSeo3A,141
|
| 149 |
+
pydantic/plugin/__init__.py,sha256=a7Tw366U6K3kltCCNZY76nc9ss-7uGGQ40TXad9OypQ,7333
|
| 150 |
+
pydantic/plugin/__pycache__/__init__.cpython-313.pyc,,
|
| 151 |
+
pydantic/plugin/__pycache__/_loader.cpython-313.pyc,,
|
| 152 |
+
pydantic/plugin/__pycache__/_schema_validator.cpython-313.pyc,,
|
| 153 |
+
pydantic/plugin/_loader.py,sha256=9QLXneLEmvyhXka_9j4Lrkbme4qPv6qYphlsjF2MGsA,2210
|
| 154 |
+
pydantic/plugin/_schema_validator.py,sha256=QbmqsG33MBmftNQ2nNiuN22LhbrexUA7ipDVv3J02BU,5267
|
| 155 |
+
pydantic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 156 |
+
pydantic/root_model.py,sha256=BvmLtW4i11dJk-dLOM3rl-jnJdQGeeQTFBcmEOq6pMg,6311
|
| 157 |
+
pydantic/schema.py,sha256=Vqqjvq_LnapVknebUd3Bp_J1p2gXZZnZRgL48bVEG7o,142
|
| 158 |
+
pydantic/tools.py,sha256=iHQpd8SJ5DCTtPV5atAV06T89bjSaMFeZZ2LX9lasZY,141
|
| 159 |
+
pydantic/type_adapter.py,sha256=VT--yg4a27shSBzWHBPKz493f3iQ9obdkEkhjZKlE7Q,35653
|
| 160 |
+
pydantic/types.py,sha256=nqdS-J2ZXqTh2qeyJOzBTBtHWyZ5YRFe8gaMV59d9HE,105431
|
| 161 |
+
pydantic/typing.py,sha256=P7feA35MwTcLsR1uL7db0S-oydBxobmXa55YDoBgajQ,138
|
| 162 |
+
pydantic/utils.py,sha256=15nR2QpqTBFlQV4TNtTItMyTJx_fbyV-gPmIEY1Gooc,141
|
| 163 |
+
pydantic/v1/__init__.py,sha256=FLQ8ISp6MVZRfjnS7fQ4m1FxQxFCF2QVikE4DK-4PhE,3164
|
| 164 |
+
pydantic/v1/__pycache__/__init__.cpython-313.pyc,,
|
| 165 |
+
pydantic/v1/__pycache__/_hypothesis_plugin.cpython-313.pyc,,
|
| 166 |
+
pydantic/v1/__pycache__/annotated_types.cpython-313.pyc,,
|
| 167 |
+
pydantic/v1/__pycache__/class_validators.cpython-313.pyc,,
|
| 168 |
+
pydantic/v1/__pycache__/color.cpython-313.pyc,,
|
| 169 |
+
pydantic/v1/__pycache__/config.cpython-313.pyc,,
|
| 170 |
+
pydantic/v1/__pycache__/dataclasses.cpython-313.pyc,,
|
| 171 |
+
pydantic/v1/__pycache__/datetime_parse.cpython-313.pyc,,
|
| 172 |
+
pydantic/v1/__pycache__/decorator.cpython-313.pyc,,
|
| 173 |
+
pydantic/v1/__pycache__/env_settings.cpython-313.pyc,,
|
| 174 |
+
pydantic/v1/__pycache__/error_wrappers.cpython-313.pyc,,
|
| 175 |
+
pydantic/v1/__pycache__/errors.cpython-313.pyc,,
|
| 176 |
+
pydantic/v1/__pycache__/fields.cpython-313.pyc,,
|
| 177 |
+
pydantic/v1/__pycache__/generics.cpython-313.pyc,,
|
| 178 |
+
pydantic/v1/__pycache__/json.cpython-313.pyc,,
|
| 179 |
+
pydantic/v1/__pycache__/main.cpython-313.pyc,,
|
| 180 |
+
pydantic/v1/__pycache__/mypy.cpython-313.pyc,,
|
| 181 |
+
pydantic/v1/__pycache__/networks.cpython-313.pyc,,
|
| 182 |
+
pydantic/v1/__pycache__/parse.cpython-313.pyc,,
|
| 183 |
+
pydantic/v1/__pycache__/schema.cpython-313.pyc,,
|
| 184 |
+
pydantic/v1/__pycache__/tools.cpython-313.pyc,,
|
| 185 |
+
pydantic/v1/__pycache__/types.cpython-313.pyc,,
|
| 186 |
+
pydantic/v1/__pycache__/typing.cpython-313.pyc,,
|
| 187 |
+
pydantic/v1/__pycache__/utils.cpython-313.pyc,,
|
| 188 |
+
pydantic/v1/__pycache__/validators.cpython-313.pyc,,
|
| 189 |
+
pydantic/v1/__pycache__/version.cpython-313.pyc,,
|
| 190 |
+
pydantic/v1/_hypothesis_plugin.py,sha256=5ES5xWuw1FQAsymLezy8QgnVz0ZpVfU3jkmT74H27VQ,14847
|
| 191 |
+
pydantic/v1/annotated_types.py,sha256=uk2NAAxqiNELKjiHhyhxKaIOh8F1lYW_LzrW3X7oZBc,3157
|
| 192 |
+
pydantic/v1/class_validators.py,sha256=ULOaIUgYUDBsHL7EEVEarcM-UubKUggoN8hSbDonsFE,14672
|
| 193 |
+
pydantic/v1/color.py,sha256=iZABLYp6OVoo2AFkP9Ipri_wSc6-Kklu8YuhSartd5g,16844
|
| 194 |
+
pydantic/v1/config.py,sha256=a6P0Wer9x4cbwKW7Xv8poSUqM4WP-RLWwX6YMpYq9AA,6532
|
| 195 |
+
pydantic/v1/dataclasses.py,sha256=784cqvInbwIPWr9usfpX3ch7z4t3J2tTK6N067_wk1o,18172
|
| 196 |
+
pydantic/v1/datetime_parse.py,sha256=4Qy1kQpq3rNVZJeIHeSPDpuS2Bvhp1KPtzJG1xu-H00,7724
|
| 197 |
+
pydantic/v1/decorator.py,sha256=zaaxxxoWPCm818D1bs0yhapRjXm32V8G0ZHWCdM1uXA,10339
|
| 198 |
+
pydantic/v1/env_settings.py,sha256=A9VXwtRl02AY-jH0C0ouy5VNw3fi6F_pkzuHDjgAAOM,14105
|
| 199 |
+
pydantic/v1/error_wrappers.py,sha256=6625Mfw9qkC2NwitB_JFAWe8B-Xv6zBU7rL9k28tfyo,5196
|
| 200 |
+
pydantic/v1/errors.py,sha256=mIwPED5vGM5Q5v4C4Z1JPldTRH-omvEylH6ksMhOmPw,17726
|
| 201 |
+
pydantic/v1/fields.py,sha256=VqWJCriUNiEyptXroDVJ501JpVA0en2VANcksqXL2b8,50649
|
| 202 |
+
pydantic/v1/generics.py,sha256=VzC9YUV-EbPpQ3aAfk1cNFej79_IzznkQ7WrmTTZS9E,17871
|
| 203 |
+
pydantic/v1/json.py,sha256=WQ5Hy_hIpfdR3YS8k6N2E6KMJzsdbBi_ldWOPJaV81M,3390
|
| 204 |
+
pydantic/v1/main.py,sha256=zuNpdN5Q0V0wG2UUTKt0HUy3XJ4OAvPSZDdiXY-FIzs,44824
|
| 205 |
+
pydantic/v1/mypy.py,sha256=Cl8XRfCmIcVE3j5AEU52C8iDh8lcX__D3hz2jIWxMAs,38860
|
| 206 |
+
pydantic/v1/networks.py,sha256=HYNtKAfOmOnKJpsDg1g6SIkj9WPhU_-i8l5e2JKBpG4,22124
|
| 207 |
+
pydantic/v1/parse.py,sha256=BJtdqiZRtav9VRFCmOxoY-KImQmjPy-A_NoojiFUZxY,1821
|
| 208 |
+
pydantic/v1/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 209 |
+
pydantic/v1/schema.py,sha256=aqBuA--cq8gAVkim5BJPFASHzOZ8dFtmFX_fNGr6ip4,47801
|
| 210 |
+
pydantic/v1/tools.py,sha256=1lDdXHk0jL5uP3u5RCYAvUAlGClgAO-45lkq9j7fyBA,2881
|
| 211 |
+
pydantic/v1/types.py,sha256=Bzl-RcnitPBHnqwwj9iv7JjHuN1GpnWH24dKkF3l9e8,35455
|
| 212 |
+
pydantic/v1/typing.py,sha256=7GdBg1YTHULU81thB_9cjRNDfZfn4khoX7nGtw_keCE,19677
|
| 213 |
+
pydantic/v1/utils.py,sha256=M5FRyfNUb1A2mk9laGgCVdfHHb3AtQgrjO5qfyBf4xA,25989
|
| 214 |
+
pydantic/v1/validators.py,sha256=lyUkn1MWhHxlCX5ZfEgFj_CAHojoiPcaQeMdEM9XviU,22187
|
| 215 |
+
pydantic/v1/version.py,sha256=HXnXW-1bMW5qKhlr5RgOEPohrZDCDSuyy8-gi8GCgZo,1039
|
| 216 |
+
pydantic/validate_call_decorator.py,sha256=8jqLlgXTjWEj4dXDg0wI3EGQKkb0JnCsL_JSUjbU5Sg,4389
|
| 217 |
+
pydantic/validators.py,sha256=pwbIJXVb1CV2mAE4w_EGfNj7DwzsKaWw_tTL6cviTus,146
|
| 218 |
+
pydantic/version.py,sha256=9B7oFVZbaIiFWijpcW6oorp9WzX-C54QiLwhqMBTSI4,3985
|
| 219 |
+
pydantic/warnings.py,sha256=Wu1VGzrvFZw4T6yCIKHjH7LSY66HjbtyCFbn5uWoMJ4,4802
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.27.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/task_176408303339170/conda-bld/pydantic_1764083529211/work"}
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic-2.12.4.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2017 to present Pydantic Services Inc. and individual contributors.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/__init__.py
ADDED
|
File without changes
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_config.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from re import Pattern
|
| 6 |
+
from typing import (
|
| 7 |
+
TYPE_CHECKING,
|
| 8 |
+
Any,
|
| 9 |
+
Callable,
|
| 10 |
+
Literal,
|
| 11 |
+
cast,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from pydantic_core import core_schema
|
| 15 |
+
from typing_extensions import Self
|
| 16 |
+
|
| 17 |
+
from ..aliases import AliasGenerator
|
| 18 |
+
from ..config import ConfigDict, ExtraValues, JsonDict, JsonEncoder, JsonSchemaExtraCallable
|
| 19 |
+
from ..errors import PydanticUserError
|
| 20 |
+
from ..warnings import PydanticDeprecatedSince20, PydanticDeprecatedSince210
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from .._internal._schema_generation_shared import GenerateSchema
|
| 24 |
+
from ..fields import ComputedFieldInfo, FieldInfo
|
| 25 |
+
|
| 26 |
+
DEPRECATION_MESSAGE = 'Support for class-based `config` is deprecated, use ConfigDict instead.'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ConfigWrapper:
|
| 30 |
+
"""Internal wrapper for Config which exposes ConfigDict items as attributes."""
|
| 31 |
+
|
| 32 |
+
__slots__ = ('config_dict',)
|
| 33 |
+
|
| 34 |
+
config_dict: ConfigDict
|
| 35 |
+
|
| 36 |
+
# all annotations are copied directly from ConfigDict, and should be kept up to date, a test will fail if they
|
| 37 |
+
# stop matching
|
| 38 |
+
title: str | None
|
| 39 |
+
str_to_lower: bool
|
| 40 |
+
str_to_upper: bool
|
| 41 |
+
str_strip_whitespace: bool
|
| 42 |
+
str_min_length: int
|
| 43 |
+
str_max_length: int | None
|
| 44 |
+
extra: ExtraValues | None
|
| 45 |
+
frozen: bool
|
| 46 |
+
populate_by_name: bool
|
| 47 |
+
use_enum_values: bool
|
| 48 |
+
validate_assignment: bool
|
| 49 |
+
arbitrary_types_allowed: bool
|
| 50 |
+
from_attributes: bool
|
| 51 |
+
# whether to use the actual key provided in the data (e.g. alias or first alias for "field required" errors) instead of field_names
|
| 52 |
+
# to construct error `loc`s, default `True`
|
| 53 |
+
loc_by_alias: bool
|
| 54 |
+
alias_generator: Callable[[str], str] | AliasGenerator | None
|
| 55 |
+
model_title_generator: Callable[[type], str] | None
|
| 56 |
+
field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
|
| 57 |
+
ignored_types: tuple[type, ...]
|
| 58 |
+
allow_inf_nan: bool
|
| 59 |
+
json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
|
| 60 |
+
json_encoders: dict[type[object], JsonEncoder] | None
|
| 61 |
+
|
| 62 |
+
# new in V2
|
| 63 |
+
strict: bool
|
| 64 |
+
# whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
|
| 65 |
+
revalidate_instances: Literal['always', 'never', 'subclass-instances']
|
| 66 |
+
ser_json_timedelta: Literal['iso8601', 'float']
|
| 67 |
+
ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
|
| 68 |
+
val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']
|
| 69 |
+
ser_json_bytes: Literal['utf8', 'base64', 'hex']
|
| 70 |
+
val_json_bytes: Literal['utf8', 'base64', 'hex']
|
| 71 |
+
ser_json_inf_nan: Literal['null', 'constants', 'strings']
|
| 72 |
+
# whether to validate default values during validation, default False
|
| 73 |
+
validate_default: bool
|
| 74 |
+
validate_return: bool
|
| 75 |
+
protected_namespaces: tuple[str | Pattern[str], ...]
|
| 76 |
+
hide_input_in_errors: bool
|
| 77 |
+
defer_build: bool
|
| 78 |
+
plugin_settings: dict[str, object] | None
|
| 79 |
+
schema_generator: type[GenerateSchema] | None
|
| 80 |
+
json_schema_serialization_defaults_required: bool
|
| 81 |
+
json_schema_mode_override: Literal['validation', 'serialization', None]
|
| 82 |
+
coerce_numbers_to_str: bool
|
| 83 |
+
regex_engine: Literal['rust-regex', 'python-re']
|
| 84 |
+
validation_error_cause: bool
|
| 85 |
+
use_attribute_docstrings: bool
|
| 86 |
+
cache_strings: bool | Literal['all', 'keys', 'none']
|
| 87 |
+
validate_by_alias: bool
|
| 88 |
+
validate_by_name: bool
|
| 89 |
+
serialize_by_alias: bool
|
| 90 |
+
url_preserve_empty_path: bool
|
| 91 |
+
|
| 92 |
+
def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True):
|
| 93 |
+
if check:
|
| 94 |
+
self.config_dict = prepare_config(config)
|
| 95 |
+
else:
|
| 96 |
+
self.config_dict = cast(ConfigDict, config)
|
| 97 |
+
|
| 98 |
+
@classmethod
|
| 99 |
+
def for_model(
|
| 100 |
+
cls,
|
| 101 |
+
bases: tuple[type[Any], ...],
|
| 102 |
+
namespace: dict[str, Any],
|
| 103 |
+
raw_annotations: dict[str, Any],
|
| 104 |
+
kwargs: dict[str, Any],
|
| 105 |
+
) -> Self:
|
| 106 |
+
"""Build a new `ConfigWrapper` instance for a `BaseModel`.
|
| 107 |
+
|
| 108 |
+
The config wrapper built based on (in descending order of priority):
|
| 109 |
+
- options from `kwargs`
|
| 110 |
+
- options from the `namespace`
|
| 111 |
+
- options from the base classes (`bases`)
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
bases: A tuple of base classes.
|
| 115 |
+
namespace: The namespace of the class being created.
|
| 116 |
+
raw_annotations: The (non-evaluated) annotations of the model.
|
| 117 |
+
kwargs: The kwargs passed to the class being created.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
A `ConfigWrapper` instance for `BaseModel`.
|
| 121 |
+
"""
|
| 122 |
+
config_new = ConfigDict()
|
| 123 |
+
for base in bases:
|
| 124 |
+
config = getattr(base, 'model_config', None)
|
| 125 |
+
if config:
|
| 126 |
+
config_new.update(config.copy())
|
| 127 |
+
|
| 128 |
+
config_class_from_namespace = namespace.get('Config')
|
| 129 |
+
config_dict_from_namespace = namespace.get('model_config')
|
| 130 |
+
|
| 131 |
+
if raw_annotations.get('model_config') and config_dict_from_namespace is None:
|
| 132 |
+
raise PydanticUserError(
|
| 133 |
+
'`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
|
| 134 |
+
code='model-config-invalid-field-name',
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
if config_class_from_namespace and config_dict_from_namespace:
|
| 138 |
+
raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both')
|
| 139 |
+
|
| 140 |
+
config_from_namespace = config_dict_from_namespace or prepare_config(config_class_from_namespace)
|
| 141 |
+
|
| 142 |
+
config_new.update(config_from_namespace)
|
| 143 |
+
|
| 144 |
+
for k in list(kwargs.keys()):
|
| 145 |
+
if k in config_keys:
|
| 146 |
+
config_new[k] = kwargs.pop(k)
|
| 147 |
+
|
| 148 |
+
return cls(config_new)
|
| 149 |
+
|
| 150 |
+
# we don't show `__getattr__` to type checkers so missing attributes cause errors
|
| 151 |
+
if not TYPE_CHECKING: # pragma: no branch
|
| 152 |
+
|
| 153 |
+
def __getattr__(self, name: str) -> Any:
|
| 154 |
+
try:
|
| 155 |
+
return self.config_dict[name]
|
| 156 |
+
except KeyError:
|
| 157 |
+
try:
|
| 158 |
+
return config_defaults[name]
|
| 159 |
+
except KeyError:
|
| 160 |
+
raise AttributeError(f'Config has no attribute {name!r}') from None
|
| 161 |
+
|
| 162 |
+
def core_config(self, title: str | None) -> core_schema.CoreConfig:
|
| 163 |
+
"""Create a pydantic-core config.
|
| 164 |
+
|
| 165 |
+
We don't use getattr here since we don't want to populate with defaults.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
title: The title to use if not set in config.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
A `CoreConfig` object created from config.
|
| 172 |
+
"""
|
| 173 |
+
config = self.config_dict
|
| 174 |
+
|
| 175 |
+
if config.get('schema_generator') is not None:
|
| 176 |
+
warnings.warn(
|
| 177 |
+
'The `schema_generator` setting has been deprecated since v2.10. This setting no longer has any effect.',
|
| 178 |
+
PydanticDeprecatedSince210,
|
| 179 |
+
stacklevel=2,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if (populate_by_name := config.get('populate_by_name')) is not None:
|
| 183 |
+
# We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.
|
| 184 |
+
# Thus, the above warning and this patch can be removed then as well.
|
| 185 |
+
if config.get('validate_by_name') is None:
|
| 186 |
+
config['validate_by_alias'] = True
|
| 187 |
+
config['validate_by_name'] = populate_by_name
|
| 188 |
+
|
| 189 |
+
# We dynamically patch validate_by_name to be True if validate_by_alias is set to False
|
| 190 |
+
# and validate_by_name is not explicitly set.
|
| 191 |
+
if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:
|
| 192 |
+
config['validate_by_name'] = True
|
| 193 |
+
|
| 194 |
+
if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):
|
| 195 |
+
raise PydanticUserError(
|
| 196 |
+
'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',
|
| 197 |
+
code='validate-by-alias-and-name-false',
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
return core_schema.CoreConfig(
|
| 201 |
+
**{ # pyright: ignore[reportArgumentType]
|
| 202 |
+
k: v
|
| 203 |
+
for k, v in (
|
| 204 |
+
('title', config.get('title') or title or None),
|
| 205 |
+
('extra_fields_behavior', config.get('extra')),
|
| 206 |
+
('allow_inf_nan', config.get('allow_inf_nan')),
|
| 207 |
+
('str_strip_whitespace', config.get('str_strip_whitespace')),
|
| 208 |
+
('str_to_lower', config.get('str_to_lower')),
|
| 209 |
+
('str_to_upper', config.get('str_to_upper')),
|
| 210 |
+
('strict', config.get('strict')),
|
| 211 |
+
('ser_json_timedelta', config.get('ser_json_timedelta')),
|
| 212 |
+
('ser_json_temporal', config.get('ser_json_temporal')),
|
| 213 |
+
('val_temporal_unit', config.get('val_temporal_unit')),
|
| 214 |
+
('ser_json_bytes', config.get('ser_json_bytes')),
|
| 215 |
+
('val_json_bytes', config.get('val_json_bytes')),
|
| 216 |
+
('ser_json_inf_nan', config.get('ser_json_inf_nan')),
|
| 217 |
+
('from_attributes', config.get('from_attributes')),
|
| 218 |
+
('loc_by_alias', config.get('loc_by_alias')),
|
| 219 |
+
('revalidate_instances', config.get('revalidate_instances')),
|
| 220 |
+
('validate_default', config.get('validate_default')),
|
| 221 |
+
('str_max_length', config.get('str_max_length')),
|
| 222 |
+
('str_min_length', config.get('str_min_length')),
|
| 223 |
+
('hide_input_in_errors', config.get('hide_input_in_errors')),
|
| 224 |
+
('coerce_numbers_to_str', config.get('coerce_numbers_to_str')),
|
| 225 |
+
('regex_engine', config.get('regex_engine')),
|
| 226 |
+
('validation_error_cause', config.get('validation_error_cause')),
|
| 227 |
+
('cache_strings', config.get('cache_strings')),
|
| 228 |
+
('validate_by_alias', config.get('validate_by_alias')),
|
| 229 |
+
('validate_by_name', config.get('validate_by_name')),
|
| 230 |
+
('serialize_by_alias', config.get('serialize_by_alias')),
|
| 231 |
+
('url_preserve_empty_path', config.get('url_preserve_empty_path')),
|
| 232 |
+
)
|
| 233 |
+
if v is not None
|
| 234 |
+
}
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def __repr__(self):
|
| 238 |
+
c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items())
|
| 239 |
+
return f'ConfigWrapper({c})'
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class ConfigWrapperStack:
|
| 243 |
+
"""A stack of `ConfigWrapper` instances."""
|
| 244 |
+
|
| 245 |
+
def __init__(self, config_wrapper: ConfigWrapper):
|
| 246 |
+
self._config_wrapper_stack: list[ConfigWrapper] = [config_wrapper]
|
| 247 |
+
|
| 248 |
+
@property
|
| 249 |
+
def tail(self) -> ConfigWrapper:
|
| 250 |
+
return self._config_wrapper_stack[-1]
|
| 251 |
+
|
| 252 |
+
@contextmanager
|
| 253 |
+
def push(self, config_wrapper: ConfigWrapper | ConfigDict | None):
|
| 254 |
+
if config_wrapper is None:
|
| 255 |
+
yield
|
| 256 |
+
return
|
| 257 |
+
|
| 258 |
+
if not isinstance(config_wrapper, ConfigWrapper):
|
| 259 |
+
config_wrapper = ConfigWrapper(config_wrapper, check=False)
|
| 260 |
+
|
| 261 |
+
self._config_wrapper_stack.append(config_wrapper)
|
| 262 |
+
try:
|
| 263 |
+
yield
|
| 264 |
+
finally:
|
| 265 |
+
self._config_wrapper_stack.pop()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
config_defaults = ConfigDict(
|
| 269 |
+
title=None,
|
| 270 |
+
str_to_lower=False,
|
| 271 |
+
str_to_upper=False,
|
| 272 |
+
str_strip_whitespace=False,
|
| 273 |
+
str_min_length=0,
|
| 274 |
+
str_max_length=None,
|
| 275 |
+
# let the model / dataclass decide how to handle it
|
| 276 |
+
extra=None,
|
| 277 |
+
frozen=False,
|
| 278 |
+
populate_by_name=False,
|
| 279 |
+
use_enum_values=False,
|
| 280 |
+
validate_assignment=False,
|
| 281 |
+
arbitrary_types_allowed=False,
|
| 282 |
+
from_attributes=False,
|
| 283 |
+
loc_by_alias=True,
|
| 284 |
+
alias_generator=None,
|
| 285 |
+
model_title_generator=None,
|
| 286 |
+
field_title_generator=None,
|
| 287 |
+
ignored_types=(),
|
| 288 |
+
allow_inf_nan=True,
|
| 289 |
+
json_schema_extra=None,
|
| 290 |
+
strict=False,
|
| 291 |
+
revalidate_instances='never',
|
| 292 |
+
ser_json_timedelta='iso8601',
|
| 293 |
+
ser_json_temporal='iso8601',
|
| 294 |
+
val_temporal_unit='infer',
|
| 295 |
+
ser_json_bytes='utf8',
|
| 296 |
+
val_json_bytes='utf8',
|
| 297 |
+
ser_json_inf_nan='null',
|
| 298 |
+
validate_default=False,
|
| 299 |
+
validate_return=False,
|
| 300 |
+
protected_namespaces=('model_validate', 'model_dump'),
|
| 301 |
+
hide_input_in_errors=False,
|
| 302 |
+
json_encoders=None,
|
| 303 |
+
defer_build=False,
|
| 304 |
+
schema_generator=None,
|
| 305 |
+
plugin_settings=None,
|
| 306 |
+
json_schema_serialization_defaults_required=False,
|
| 307 |
+
json_schema_mode_override=None,
|
| 308 |
+
coerce_numbers_to_str=False,
|
| 309 |
+
regex_engine='rust-regex',
|
| 310 |
+
validation_error_cause=False,
|
| 311 |
+
use_attribute_docstrings=False,
|
| 312 |
+
cache_strings=True,
|
| 313 |
+
validate_by_alias=True,
|
| 314 |
+
validate_by_name=False,
|
| 315 |
+
serialize_by_alias=False,
|
| 316 |
+
url_preserve_empty_path=False,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def prepare_config(config: ConfigDict | dict[str, Any] | type[Any] | None) -> ConfigDict:
|
| 321 |
+
"""Create a `ConfigDict` instance from an existing dict, a class (e.g. old class-based config) or None.
|
| 322 |
+
|
| 323 |
+
Args:
|
| 324 |
+
config: The input config.
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
A ConfigDict object created from config.
|
| 328 |
+
"""
|
| 329 |
+
if config is None:
|
| 330 |
+
return ConfigDict()
|
| 331 |
+
|
| 332 |
+
if not isinstance(config, dict):
|
| 333 |
+
warnings.warn(DEPRECATION_MESSAGE, PydanticDeprecatedSince20, stacklevel=4)
|
| 334 |
+
config = {k: getattr(config, k) for k in dir(config) if not k.startswith('__')}
|
| 335 |
+
|
| 336 |
+
config_dict = cast(ConfigDict, config)
|
| 337 |
+
check_deprecated(config_dict)
|
| 338 |
+
return config_dict
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
config_keys = set(ConfigDict.__annotations__.keys())
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
V2_REMOVED_KEYS = {
|
| 345 |
+
'allow_mutation',
|
| 346 |
+
'error_msg_templates',
|
| 347 |
+
'fields',
|
| 348 |
+
'getter_dict',
|
| 349 |
+
'smart_union',
|
| 350 |
+
'underscore_attrs_are_private',
|
| 351 |
+
'json_loads',
|
| 352 |
+
'json_dumps',
|
| 353 |
+
'copy_on_model_validation',
|
| 354 |
+
'post_init_call',
|
| 355 |
+
}
|
| 356 |
+
V2_RENAMED_KEYS = {
|
| 357 |
+
'allow_population_by_field_name': 'validate_by_name',
|
| 358 |
+
'anystr_lower': 'str_to_lower',
|
| 359 |
+
'anystr_strip_whitespace': 'str_strip_whitespace',
|
| 360 |
+
'anystr_upper': 'str_to_upper',
|
| 361 |
+
'keep_untouched': 'ignored_types',
|
| 362 |
+
'max_anystr_length': 'str_max_length',
|
| 363 |
+
'min_anystr_length': 'str_min_length',
|
| 364 |
+
'orm_mode': 'from_attributes',
|
| 365 |
+
'schema_extra': 'json_schema_extra',
|
| 366 |
+
'validate_all': 'validate_default',
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def check_deprecated(config_dict: ConfigDict) -> None:
|
| 371 |
+
"""Check for deprecated config keys and warn the user.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
config_dict: The input config.
|
| 375 |
+
"""
|
| 376 |
+
deprecated_removed_keys = V2_REMOVED_KEYS & config_dict.keys()
|
| 377 |
+
deprecated_renamed_keys = V2_RENAMED_KEYS.keys() & config_dict.keys()
|
| 378 |
+
if deprecated_removed_keys or deprecated_renamed_keys:
|
| 379 |
+
renamings = {k: V2_RENAMED_KEYS[k] for k in sorted(deprecated_renamed_keys)}
|
| 380 |
+
renamed_bullets = [f'* {k!r} has been renamed to {v!r}' for k, v in renamings.items()]
|
| 381 |
+
removed_bullets = [f'* {k!r} has been removed' for k in sorted(deprecated_removed_keys)]
|
| 382 |
+
message = '\n'.join(['Valid config keys have changed in V2:'] + renamed_bullets + removed_bullets)
|
| 383 |
+
warnings.warn(message, UserWarning)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_core_metadata.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
| 4 |
+
from warnings import warn
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from ..config import JsonDict, JsonSchemaExtraCallable
|
| 8 |
+
from ._schema_generation_shared import (
|
| 9 |
+
GetJsonSchemaFunction,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CoreMetadata(TypedDict, total=False):
|
| 14 |
+
"""A `TypedDict` for holding the metadata dict of the schema.
|
| 15 |
+
|
| 16 |
+
Attributes:
|
| 17 |
+
pydantic_js_functions: List of JSON schema functions that resolve refs during application.
|
| 18 |
+
pydantic_js_annotation_functions: List of JSON schema functions that don't resolve refs during application.
|
| 19 |
+
pydantic_js_prefer_positional_arguments: Whether JSON schema generator will
|
| 20 |
+
prefer positional over keyword arguments for an 'arguments' schema.
|
| 21 |
+
custom validation function. Only applies to before, plain, and wrap validators.
|
| 22 |
+
pydantic_js_updates: key / value pair updates to apply to the JSON schema for a type.
|
| 23 |
+
pydantic_js_extra: WIP, either key/value pair updates to apply to the JSON schema, or a custom callable.
|
| 24 |
+
pydantic_internal_union_tag_key: Used internally by the `Tag` metadata to specify the tag used for a discriminated union.
|
| 25 |
+
pydantic_internal_union_discriminator: Used internally to specify the discriminator value for a discriminated union
|
| 26 |
+
when the discriminator was applied to a `'definition-ref'` schema, and that reference was missing at the time
|
| 27 |
+
of the annotation application.
|
| 28 |
+
|
| 29 |
+
TODO: Perhaps we should move this structure to pydantic-core. At the moment, though,
|
| 30 |
+
it's easier to iterate on if we leave it in pydantic until we feel there is a semi-stable API.
|
| 31 |
+
|
| 32 |
+
TODO: It's unfortunate how functionally oriented JSON schema generation is, especially that which occurs during
|
| 33 |
+
the core schema generation process. It's inevitable that we need to store some json schema related information
|
| 34 |
+
on core schemas, given that we generate JSON schemas directly from core schemas. That being said, debugging related
|
| 35 |
+
issues is quite difficult when JSON schema information is disguised via dynamically defined functions.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
pydantic_js_functions: list[GetJsonSchemaFunction]
|
| 39 |
+
pydantic_js_annotation_functions: list[GetJsonSchemaFunction]
|
| 40 |
+
pydantic_js_prefer_positional_arguments: bool
|
| 41 |
+
pydantic_js_updates: JsonDict
|
| 42 |
+
pydantic_js_extra: JsonDict | JsonSchemaExtraCallable
|
| 43 |
+
pydantic_internal_union_tag_key: str
|
| 44 |
+
pydantic_internal_union_discriminator: str
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def update_core_metadata(
|
| 48 |
+
core_metadata: Any,
|
| 49 |
+
/,
|
| 50 |
+
*,
|
| 51 |
+
pydantic_js_functions: list[GetJsonSchemaFunction] | None = None,
|
| 52 |
+
pydantic_js_annotation_functions: list[GetJsonSchemaFunction] | None = None,
|
| 53 |
+
pydantic_js_updates: JsonDict | None = None,
|
| 54 |
+
pydantic_js_extra: JsonDict | JsonSchemaExtraCallable | None = None,
|
| 55 |
+
) -> None:
|
| 56 |
+
from ..json_schema import PydanticJsonSchemaWarning
|
| 57 |
+
|
| 58 |
+
"""Update CoreMetadata instance in place. When we make modifications in this function, they
|
| 59 |
+
take effect on the `core_metadata` reference passed in as the first (and only) positional argument.
|
| 60 |
+
|
| 61 |
+
First, cast to `CoreMetadata`, then finish with a cast to `dict[str, Any]` for core schema compatibility.
|
| 62 |
+
We do this here, instead of before / after each call to this function so that this typing hack
|
| 63 |
+
can be easily removed if/when we move `CoreMetadata` to `pydantic-core`.
|
| 64 |
+
|
| 65 |
+
For parameter descriptions, see `CoreMetadata` above.
|
| 66 |
+
"""
|
| 67 |
+
core_metadata = cast(CoreMetadata, core_metadata)
|
| 68 |
+
|
| 69 |
+
if pydantic_js_functions:
|
| 70 |
+
core_metadata.setdefault('pydantic_js_functions', []).extend(pydantic_js_functions)
|
| 71 |
+
|
| 72 |
+
if pydantic_js_annotation_functions:
|
| 73 |
+
core_metadata.setdefault('pydantic_js_annotation_functions', []).extend(pydantic_js_annotation_functions)
|
| 74 |
+
|
| 75 |
+
if pydantic_js_updates:
|
| 76 |
+
if (existing_updates := core_metadata.get('pydantic_js_updates')) is not None:
|
| 77 |
+
core_metadata['pydantic_js_updates'] = {**existing_updates, **pydantic_js_updates}
|
| 78 |
+
else:
|
| 79 |
+
core_metadata['pydantic_js_updates'] = pydantic_js_updates
|
| 80 |
+
|
| 81 |
+
if pydantic_js_extra is not None:
|
| 82 |
+
existing_pydantic_js_extra = core_metadata.get('pydantic_js_extra')
|
| 83 |
+
if existing_pydantic_js_extra is None:
|
| 84 |
+
core_metadata['pydantic_js_extra'] = pydantic_js_extra
|
| 85 |
+
if isinstance(existing_pydantic_js_extra, dict):
|
| 86 |
+
if isinstance(pydantic_js_extra, dict):
|
| 87 |
+
core_metadata['pydantic_js_extra'] = {**existing_pydantic_js_extra, **pydantic_js_extra}
|
| 88 |
+
if callable(pydantic_js_extra):
|
| 89 |
+
warn(
|
| 90 |
+
'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
|
| 91 |
+
'The `callable` type is being ignored.'
|
| 92 |
+
"If you'd like support for this behavior, please open an issue on pydantic.",
|
| 93 |
+
PydanticJsonSchemaWarning,
|
| 94 |
+
)
|
| 95 |
+
if callable(existing_pydantic_js_extra):
|
| 96 |
+
# if ever there's a case of a callable, we'll just keep the last json schema extra spec
|
| 97 |
+
core_metadata['pydantic_js_extra'] = pydantic_js_extra
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_core_utils.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
from collections.abc import Mapping, Sequence
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 6 |
+
|
| 7 |
+
from pydantic_core import CoreSchema, core_schema
|
| 8 |
+
from typing_extensions import TypeGuard, get_args, get_origin
|
| 9 |
+
from typing_inspection import typing_objects
|
| 10 |
+
|
| 11 |
+
from . import _repr
|
| 12 |
+
from ._typing_extra import is_generic_alias
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from rich.console import Console
|
| 16 |
+
|
| 17 |
+
AnyFunctionSchema = Union[
|
| 18 |
+
core_schema.AfterValidatorFunctionSchema,
|
| 19 |
+
core_schema.BeforeValidatorFunctionSchema,
|
| 20 |
+
core_schema.WrapValidatorFunctionSchema,
|
| 21 |
+
core_schema.PlainValidatorFunctionSchema,
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
FunctionSchemaWithInnerSchema = Union[
|
| 26 |
+
core_schema.AfterValidatorFunctionSchema,
|
| 27 |
+
core_schema.BeforeValidatorFunctionSchema,
|
| 28 |
+
core_schema.WrapValidatorFunctionSchema,
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
CoreSchemaField = Union[
|
| 32 |
+
core_schema.ModelField, core_schema.DataclassField, core_schema.TypedDictField, core_schema.ComputedField
|
| 33 |
+
]
|
| 34 |
+
CoreSchemaOrField = Union[core_schema.CoreSchema, CoreSchemaField]
|
| 35 |
+
|
| 36 |
+
_CORE_SCHEMA_FIELD_TYPES = {'typed-dict-field', 'dataclass-field', 'model-field', 'computed-field'}
|
| 37 |
+
_FUNCTION_WITH_INNER_SCHEMA_TYPES = {'function-before', 'function-after', 'function-wrap'}
|
| 38 |
+
_LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES = {'list', 'set', 'frozenset'}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def is_core_schema(
|
| 42 |
+
schema: CoreSchemaOrField,
|
| 43 |
+
) -> TypeGuard[CoreSchema]:
|
| 44 |
+
return schema['type'] not in _CORE_SCHEMA_FIELD_TYPES
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def is_core_schema_field(
|
| 48 |
+
schema: CoreSchemaOrField,
|
| 49 |
+
) -> TypeGuard[CoreSchemaField]:
|
| 50 |
+
return schema['type'] in _CORE_SCHEMA_FIELD_TYPES
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def is_function_with_inner_schema(
|
| 54 |
+
schema: CoreSchemaOrField,
|
| 55 |
+
) -> TypeGuard[FunctionSchemaWithInnerSchema]:
|
| 56 |
+
return schema['type'] in _FUNCTION_WITH_INNER_SCHEMA_TYPES
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def is_list_like_schema_with_items_schema(
|
| 60 |
+
schema: CoreSchema,
|
| 61 |
+
) -> TypeGuard[core_schema.ListSchema | core_schema.SetSchema | core_schema.FrozenSetSchema]:
|
| 62 |
+
return schema['type'] in _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_type_ref(type_: Any, args_override: tuple[type[Any], ...] | None = None) -> str:
|
| 66 |
+
"""Produces the ref to be used for this type by pydantic_core's core schemas.
|
| 67 |
+
|
| 68 |
+
This `args_override` argument was added for the purpose of creating valid recursive references
|
| 69 |
+
when creating generic models without needing to create a concrete class.
|
| 70 |
+
"""
|
| 71 |
+
origin = get_origin(type_) or type_
|
| 72 |
+
|
| 73 |
+
args = get_args(type_) if is_generic_alias(type_) else (args_override or ())
|
| 74 |
+
generic_metadata = getattr(type_, '__pydantic_generic_metadata__', None)
|
| 75 |
+
if generic_metadata:
|
| 76 |
+
origin = generic_metadata['origin'] or origin
|
| 77 |
+
args = generic_metadata['args'] or args
|
| 78 |
+
|
| 79 |
+
module_name = getattr(origin, '__module__', '<No __module__>')
|
| 80 |
+
if typing_objects.is_typealiastype(origin):
|
| 81 |
+
type_ref = f'{module_name}.{origin.__name__}:{id(origin)}'
|
| 82 |
+
else:
|
| 83 |
+
try:
|
| 84 |
+
qualname = getattr(origin, '__qualname__', f'<No __qualname__: {origin}>')
|
| 85 |
+
except Exception:
|
| 86 |
+
qualname = getattr(origin, '__qualname__', '<No __qualname__>')
|
| 87 |
+
type_ref = f'{module_name}.{qualname}:{id(origin)}'
|
| 88 |
+
|
| 89 |
+
arg_refs: list[str] = []
|
| 90 |
+
for arg in args:
|
| 91 |
+
if isinstance(arg, str):
|
| 92 |
+
# Handle string literals as a special case; we may be able to remove this special handling if we
|
| 93 |
+
# wrap them in a ForwardRef at some point.
|
| 94 |
+
arg_ref = f'{arg}:str-{id(arg)}'
|
| 95 |
+
else:
|
| 96 |
+
arg_ref = f'{_repr.display_as_type(arg)}:{id(arg)}'
|
| 97 |
+
arg_refs.append(arg_ref)
|
| 98 |
+
if arg_refs:
|
| 99 |
+
type_ref = f'{type_ref}[{",".join(arg_refs)}]'
|
| 100 |
+
return type_ref
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_ref(s: core_schema.CoreSchema) -> None | str:
|
| 104 |
+
"""Get the ref from the schema if it has one.
|
| 105 |
+
This exists just for type checking to work correctly.
|
| 106 |
+
"""
|
| 107 |
+
return s.get('ref', None)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _clean_schema_for_pretty_print(obj: Any, strip_metadata: bool = True) -> Any: # pragma: no cover
|
| 111 |
+
"""A utility function to remove irrelevant information from a core schema."""
|
| 112 |
+
if isinstance(obj, Mapping):
|
| 113 |
+
new_dct = {}
|
| 114 |
+
for k, v in obj.items():
|
| 115 |
+
if k == 'metadata' and strip_metadata:
|
| 116 |
+
new_metadata = {}
|
| 117 |
+
|
| 118 |
+
for meta_k, meta_v in v.items():
|
| 119 |
+
if meta_k in ('pydantic_js_functions', 'pydantic_js_annotation_functions'):
|
| 120 |
+
new_metadata['js_metadata'] = '<stripped>'
|
| 121 |
+
else:
|
| 122 |
+
new_metadata[meta_k] = _clean_schema_for_pretty_print(meta_v, strip_metadata=strip_metadata)
|
| 123 |
+
|
| 124 |
+
if list(new_metadata.keys()) == ['js_metadata']:
|
| 125 |
+
new_metadata = {'<stripped>'}
|
| 126 |
+
|
| 127 |
+
new_dct[k] = new_metadata
|
| 128 |
+
# Remove some defaults:
|
| 129 |
+
elif k in ('custom_init', 'root_model') and not v:
|
| 130 |
+
continue
|
| 131 |
+
else:
|
| 132 |
+
new_dct[k] = _clean_schema_for_pretty_print(v, strip_metadata=strip_metadata)
|
| 133 |
+
|
| 134 |
+
return new_dct
|
| 135 |
+
elif isinstance(obj, Sequence) and not isinstance(obj, str):
|
| 136 |
+
return [_clean_schema_for_pretty_print(v, strip_metadata=strip_metadata) for v in obj]
|
| 137 |
+
else:
|
| 138 |
+
return obj
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def pretty_print_core_schema(
|
| 142 |
+
val: Any,
|
| 143 |
+
*,
|
| 144 |
+
console: Console | None = None,
|
| 145 |
+
max_depth: int | None = None,
|
| 146 |
+
strip_metadata: bool = True,
|
| 147 |
+
) -> None: # pragma: no cover
|
| 148 |
+
"""Pretty-print a core schema using the `rich` library.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
val: The core schema to print, or a Pydantic model/dataclass/type adapter
|
| 152 |
+
(in which case the cached core schema is fetched and printed).
|
| 153 |
+
console: A rich console to use when printing. Defaults to the global rich console instance.
|
| 154 |
+
max_depth: The number of nesting levels which may be printed.
|
| 155 |
+
strip_metadata: Whether to strip metadata in the output. If `True` any known core metadata
|
| 156 |
+
attributes will be stripped (but custom attributes are kept). Defaults to `True`.
|
| 157 |
+
"""
|
| 158 |
+
# lazy import:
|
| 159 |
+
from rich.pretty import pprint
|
| 160 |
+
|
| 161 |
+
# circ. imports:
|
| 162 |
+
from pydantic import BaseModel, TypeAdapter
|
| 163 |
+
from pydantic.dataclasses import is_pydantic_dataclass
|
| 164 |
+
|
| 165 |
+
if (inspect.isclass(val) and issubclass(val, BaseModel)) or is_pydantic_dataclass(val):
|
| 166 |
+
val = val.__pydantic_core_schema__
|
| 167 |
+
if isinstance(val, TypeAdapter):
|
| 168 |
+
val = val.core_schema
|
| 169 |
+
cleaned_schema = _clean_schema_for_pretty_print(val, strip_metadata=strip_metadata)
|
| 170 |
+
|
| 171 |
+
pprint(cleaned_schema, console=console, max_depth=max_depth)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
pps = pretty_print_core_schema
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_dataclasses.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private logic for creating pydantic dataclasses."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import dataclasses
|
| 7 |
+
import sys
|
| 8 |
+
import warnings
|
| 9 |
+
from collections.abc import Generator
|
| 10 |
+
from contextlib import contextmanager
|
| 11 |
+
from functools import partial
|
| 12 |
+
from typing import TYPE_CHECKING, Any, ClassVar, Protocol, cast
|
| 13 |
+
|
| 14 |
+
from pydantic_core import (
|
| 15 |
+
ArgsKwargs,
|
| 16 |
+
SchemaSerializer,
|
| 17 |
+
SchemaValidator,
|
| 18 |
+
core_schema,
|
| 19 |
+
)
|
| 20 |
+
from typing_extensions import TypeAlias, TypeIs
|
| 21 |
+
|
| 22 |
+
from ..errors import PydanticUndefinedAnnotation
|
| 23 |
+
from ..fields import FieldInfo
|
| 24 |
+
from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator
|
| 25 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 26 |
+
from . import _config, _decorators
|
| 27 |
+
from ._fields import collect_dataclass_fields
|
| 28 |
+
from ._generate_schema import GenerateSchema, InvalidSchemaError
|
| 29 |
+
from ._generics import get_standard_typevars_map
|
| 30 |
+
from ._mock_val_ser import set_dataclass_mocks
|
| 31 |
+
from ._namespace_utils import NsResolver
|
| 32 |
+
from ._signature import generate_pydantic_signature
|
| 33 |
+
from ._utils import LazyClassAttribute
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from _typeshed import DataclassInstance as StandardDataclass
|
| 37 |
+
|
| 38 |
+
from ..config import ConfigDict
|
| 39 |
+
|
| 40 |
+
class PydanticDataclass(StandardDataclass, Protocol):
|
| 41 |
+
"""A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.
|
| 42 |
+
|
| 43 |
+
Attributes:
|
| 44 |
+
__pydantic_config__: Pydantic-specific configuration settings for the dataclass.
|
| 45 |
+
__pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields.
|
| 46 |
+
__pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
|
| 47 |
+
__pydantic_decorators__: Metadata containing the decorators defined on the dataclass.
|
| 48 |
+
__pydantic_fields__: Metadata about the fields defined on the dataclass.
|
| 49 |
+
__pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass.
|
| 50 |
+
__pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
__pydantic_config__: ClassVar[ConfigDict]
|
| 54 |
+
__pydantic_complete__: ClassVar[bool]
|
| 55 |
+
__pydantic_core_schema__: ClassVar[core_schema.CoreSchema]
|
| 56 |
+
__pydantic_decorators__: ClassVar[_decorators.DecoratorInfos]
|
| 57 |
+
__pydantic_fields__: ClassVar[dict[str, FieldInfo]]
|
| 58 |
+
__pydantic_serializer__: ClassVar[SchemaSerializer]
|
| 59 |
+
__pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def __pydantic_fields_complete__(cls) -> bool: ...
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def set_dataclass_fields(
|
| 66 |
+
cls: type[StandardDataclass],
|
| 67 |
+
config_wrapper: _config.ConfigWrapper,
|
| 68 |
+
ns_resolver: NsResolver | None = None,
|
| 69 |
+
) -> None:
|
| 70 |
+
"""Collect and set `cls.__pydantic_fields__`.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
cls: The class.
|
| 74 |
+
config_wrapper: The config wrapper instance.
|
| 75 |
+
ns_resolver: Namespace resolver to use when getting dataclass annotations.
|
| 76 |
+
"""
|
| 77 |
+
typevars_map = get_standard_typevars_map(cls)
|
| 78 |
+
fields = collect_dataclass_fields(
|
| 79 |
+
cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
cls.__pydantic_fields__ = fields # type: ignore
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def complete_dataclass(
|
| 86 |
+
cls: type[Any],
|
| 87 |
+
config_wrapper: _config.ConfigWrapper,
|
| 88 |
+
*,
|
| 89 |
+
raise_errors: bool = True,
|
| 90 |
+
ns_resolver: NsResolver | None = None,
|
| 91 |
+
_force_build: bool = False,
|
| 92 |
+
) -> bool:
|
| 93 |
+
"""Finish building a pydantic dataclass.
|
| 94 |
+
|
| 95 |
+
This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`.
|
| 96 |
+
|
| 97 |
+
This is somewhat analogous to `pydantic._internal._model_construction.complete_model_class`.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
cls: The class.
|
| 101 |
+
config_wrapper: The config wrapper instance.
|
| 102 |
+
raise_errors: Whether to raise errors, defaults to `True`.
|
| 103 |
+
ns_resolver: The namespace resolver instance to use when collecting dataclass fields
|
| 104 |
+
and during schema building.
|
| 105 |
+
_force_build: Whether to force building the dataclass, no matter if
|
| 106 |
+
[`defer_build`][pydantic.config.ConfigDict.defer_build] is set.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
`True` if building a pydantic dataclass is successfully completed, `False` otherwise.
|
| 110 |
+
|
| 111 |
+
Raises:
|
| 112 |
+
PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations.
|
| 113 |
+
"""
|
| 114 |
+
original_init = cls.__init__
|
| 115 |
+
|
| 116 |
+
# dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied,
|
| 117 |
+
# and so that the mock validator is used if building was deferred:
|
| 118 |
+
def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None:
|
| 119 |
+
__tracebackhide__ = True
|
| 120 |
+
s = __dataclass_self__
|
| 121 |
+
s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s)
|
| 122 |
+
|
| 123 |
+
__init__.__qualname__ = f'{cls.__qualname__}.__init__'
|
| 124 |
+
|
| 125 |
+
cls.__init__ = __init__ # type: ignore
|
| 126 |
+
cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore
|
| 127 |
+
|
| 128 |
+
set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
|
| 129 |
+
|
| 130 |
+
if not _force_build and config_wrapper.defer_build:
|
| 131 |
+
set_dataclass_mocks(cls)
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
if hasattr(cls, '__post_init_post_parse__'):
|
| 135 |
+
warnings.warn(
|
| 136 |
+
'Support for `__post_init_post_parse__` has been dropped, the method will not be called',
|
| 137 |
+
PydanticDeprecatedSince20,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
typevars_map = get_standard_typevars_map(cls)
|
| 141 |
+
gen_schema = GenerateSchema(
|
| 142 |
+
config_wrapper,
|
| 143 |
+
ns_resolver=ns_resolver,
|
| 144 |
+
typevars_map=typevars_map,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# set __signature__ attr only for the class, but not for its instances
|
| 148 |
+
# (because instances can define `__call__`, and `inspect.signature` shouldn't
|
| 149 |
+
# use the `__signature__` attribute and instead generate from `__call__`).
|
| 150 |
+
cls.__signature__ = LazyClassAttribute(
|
| 151 |
+
'__signature__',
|
| 152 |
+
partial(
|
| 153 |
+
generate_pydantic_signature,
|
| 154 |
+
# It's important that we reference the `original_init` here,
|
| 155 |
+
# as it is the one synthesized by the stdlib `dataclass` module:
|
| 156 |
+
init=original_init,
|
| 157 |
+
fields=cls.__pydantic_fields__, # type: ignore
|
| 158 |
+
validate_by_name=config_wrapper.validate_by_name,
|
| 159 |
+
extra=config_wrapper.extra,
|
| 160 |
+
is_dataclass=True,
|
| 161 |
+
),
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
schema = gen_schema.generate_schema(cls)
|
| 166 |
+
except PydanticUndefinedAnnotation as e:
|
| 167 |
+
if raise_errors:
|
| 168 |
+
raise
|
| 169 |
+
set_dataclass_mocks(cls, f'`{e.name}`')
|
| 170 |
+
return False
|
| 171 |
+
|
| 172 |
+
core_config = config_wrapper.core_config(title=cls.__name__)
|
| 173 |
+
|
| 174 |
+
try:
|
| 175 |
+
schema = gen_schema.clean_schema(schema)
|
| 176 |
+
except InvalidSchemaError:
|
| 177 |
+
set_dataclass_mocks(cls)
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
# We are about to set all the remaining required properties expected for this cast;
|
| 181 |
+
# __pydantic_decorators__ and __pydantic_fields__ should already be set
|
| 182 |
+
cls = cast('type[PydanticDataclass]', cls)
|
| 183 |
+
|
| 184 |
+
cls.__pydantic_core_schema__ = schema
|
| 185 |
+
cls.__pydantic_validator__ = create_schema_validator(
|
| 186 |
+
schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings
|
| 187 |
+
)
|
| 188 |
+
cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config)
|
| 189 |
+
cls.__pydantic_complete__ = True
|
| 190 |
+
return True
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]:
|
| 194 |
+
"""Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass.
|
| 195 |
+
|
| 196 |
+
Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses
|
| 197 |
+
of a dataclass that are themselves not dataclasses.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
cls: The class.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
`True` if the class is a stdlib dataclass, `False` otherwise.
|
| 204 |
+
"""
|
| 205 |
+
return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__')
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def as_dataclass_field(pydantic_field: FieldInfo) -> dataclasses.Field[Any]:
|
| 209 |
+
field_args: dict[str, Any] = {'default': pydantic_field}
|
| 210 |
+
|
| 211 |
+
# Needed because if `doc` is set, the dataclass slots will be a dict (field name -> doc) instead of a tuple:
|
| 212 |
+
if sys.version_info >= (3, 14) and pydantic_field.description is not None:
|
| 213 |
+
field_args['doc'] = pydantic_field.description
|
| 214 |
+
|
| 215 |
+
# Needed as the stdlib dataclass module processes kw_only in a specific way during class construction:
|
| 216 |
+
if sys.version_info >= (3, 10) and pydantic_field.kw_only:
|
| 217 |
+
field_args['kw_only'] = True
|
| 218 |
+
|
| 219 |
+
# Needed as the stdlib dataclass modules generates `__repr__()` during class construction:
|
| 220 |
+
if pydantic_field.repr is not True:
|
| 221 |
+
field_args['repr'] = pydantic_field.repr
|
| 222 |
+
|
| 223 |
+
return dataclasses.field(**field_args)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
DcFields: TypeAlias = dict[str, dataclasses.Field[Any]]
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@contextmanager
|
| 230 |
+
def patch_base_fields(cls: type[Any]) -> Generator[None]:
|
| 231 |
+
"""Temporarily patch the stdlib dataclasses bases of `cls` if the Pydantic `Field()` function is used.
|
| 232 |
+
|
| 233 |
+
When creating a Pydantic dataclass, it is possible to inherit from stdlib dataclasses, where
|
| 234 |
+
the Pydantic `Field()` function is used. To create this Pydantic dataclass, we first apply
|
| 235 |
+
the stdlib `@dataclass` decorator on it. During the construction of the stdlib dataclass,
|
| 236 |
+
the `kw_only` and `repr` field arguments need to be understood by the stdlib *during* the
|
| 237 |
+
dataclass construction. To do so, we temporarily patch the fields dictionary of the affected
|
| 238 |
+
bases.
|
| 239 |
+
|
| 240 |
+
For instance, with the following example:
|
| 241 |
+
|
| 242 |
+
```python {test="skip" lint="skip"}
|
| 243 |
+
import dataclasses as stdlib_dc
|
| 244 |
+
|
| 245 |
+
import pydantic
|
| 246 |
+
import pydantic.dataclasses as pydantic_dc
|
| 247 |
+
|
| 248 |
+
@stdlib_dc.dataclass
|
| 249 |
+
class A:
|
| 250 |
+
a: int = pydantic.Field(repr=False)
|
| 251 |
+
|
| 252 |
+
# Notice that the `repr` attribute of the dataclass field is `True`:
|
| 253 |
+
A.__dataclass_fields__['a']
|
| 254 |
+
#> dataclass.Field(default=FieldInfo(repr=False), repr=True, ...)
|
| 255 |
+
|
| 256 |
+
@pydantic_dc.dataclass
|
| 257 |
+
class B(A):
|
| 258 |
+
b: int = pydantic.Field(repr=False)
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
When passing `B` to the stdlib `@dataclass` decorator, it will look for fields in the parent classes
|
| 262 |
+
and reuse them directly. When this context manager is active, `A` will be temporarily patched to be
|
| 263 |
+
equivalent to:
|
| 264 |
+
|
| 265 |
+
```python {test="skip" lint="skip"}
|
| 266 |
+
@stdlib_dc.dataclass
|
| 267 |
+
class A:
|
| 268 |
+
a: int = stdlib_dc.field(default=Field(repr=False), repr=False)
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
!!! note
|
| 272 |
+
This is only applied to the bases of `cls`, and not `cls` itself. The reason is that the Pydantic
|
| 273 |
+
dataclass decorator "owns" `cls` (in the previous example, `B`). As such, we instead modify the fields
|
| 274 |
+
directly (in the previous example, we simply do `setattr(B, 'b', as_dataclass_field(pydantic_field))`).
|
| 275 |
+
|
| 276 |
+
!!! note
|
| 277 |
+
This approach is far from ideal, and can probably be the source of unwanted side effects/race conditions.
|
| 278 |
+
The previous implemented approach was mutating the `__annotations__` dict of `cls`, which is no longer a
|
| 279 |
+
safe operation in Python 3.14+, and resulted in unexpected behavior with field ordering anyway.
|
| 280 |
+
"""
|
| 281 |
+
# A list of two-tuples, the first element being a reference to the
|
| 282 |
+
# dataclass fields dictionary, the second element being a mapping between
|
| 283 |
+
# the field names that were modified, and their original `Field`:
|
| 284 |
+
original_fields_list: list[tuple[DcFields, DcFields]] = []
|
| 285 |
+
|
| 286 |
+
for base in cls.__mro__[1:]:
|
| 287 |
+
dc_fields: dict[str, dataclasses.Field[Any]] = base.__dict__.get('__dataclass_fields__', {})
|
| 288 |
+
dc_fields_with_pydantic_field_defaults = {
|
| 289 |
+
field_name: field
|
| 290 |
+
for field_name, field in dc_fields.items()
|
| 291 |
+
if isinstance(field.default, FieldInfo)
|
| 292 |
+
# Only do the patching if one of the affected attributes is set:
|
| 293 |
+
and (field.default.description is not None or field.default.kw_only or field.default.repr is not True)
|
| 294 |
+
}
|
| 295 |
+
if dc_fields_with_pydantic_field_defaults:
|
| 296 |
+
original_fields_list.append((dc_fields, dc_fields_with_pydantic_field_defaults))
|
| 297 |
+
for field_name, field in dc_fields_with_pydantic_field_defaults.items():
|
| 298 |
+
default = cast(FieldInfo, field.default)
|
| 299 |
+
# `dataclasses.Field` isn't documented as working with `copy.copy()`.
|
| 300 |
+
# It is a class with `__slots__`, so should work (and we hope for the best):
|
| 301 |
+
new_dc_field = copy.copy(field)
|
| 302 |
+
# For base fields, no need to set `doc` from `FieldInfo.description`, this is only relevant
|
| 303 |
+
# for the class under construction and handled in `as_dataclass_field()`.
|
| 304 |
+
if sys.version_info >= (3, 10) and default.kw_only:
|
| 305 |
+
new_dc_field.kw_only = True
|
| 306 |
+
if default.repr is not True:
|
| 307 |
+
new_dc_field.repr = default.repr
|
| 308 |
+
dc_fields[field_name] = new_dc_field
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
yield
|
| 312 |
+
finally:
|
| 313 |
+
for fields, original_fields in original_fields_list:
|
| 314 |
+
for field_name, original_field in original_fields.items():
|
| 315 |
+
fields[field_name] = original_field
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_decorators.py
ADDED
|
@@ -0,0 +1,858 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logic related to validators applied to models etc. via the `@field_validator` and `@model_validator` decorators."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import types
|
| 7 |
+
from collections import deque
|
| 8 |
+
from collections.abc import Iterable
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from functools import cached_property, partial, partialmethod
|
| 11 |
+
from inspect import Parameter, Signature, isdatadescriptor, ismethoddescriptor, signature
|
| 12 |
+
from itertools import islice
|
| 13 |
+
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, Literal, TypeVar, Union
|
| 14 |
+
|
| 15 |
+
from pydantic_core import PydanticUndefined, PydanticUndefinedType, core_schema
|
| 16 |
+
from typing_extensions import TypeAlias, is_typeddict
|
| 17 |
+
|
| 18 |
+
from ..errors import PydanticUserError
|
| 19 |
+
from ._core_utils import get_type_ref
|
| 20 |
+
from ._internal_dataclass import slots_true
|
| 21 |
+
from ._namespace_utils import GlobalsNamespace, MappingNamespace
|
| 22 |
+
from ._typing_extra import get_function_type_hints
|
| 23 |
+
from ._utils import can_be_positional
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from ..fields import ComputedFieldInfo
|
| 27 |
+
from ..functional_validators import FieldValidatorModes
|
| 28 |
+
from ._config import ConfigWrapper
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(**slots_true)
|
| 32 |
+
class ValidatorDecoratorInfo:
|
| 33 |
+
"""A container for data from `@validator` so that we can access it
|
| 34 |
+
while building the pydantic-core schema.
|
| 35 |
+
|
| 36 |
+
Attributes:
|
| 37 |
+
decorator_repr: A class variable representing the decorator string, '@validator'.
|
| 38 |
+
fields: A tuple of field names the validator should be called on.
|
| 39 |
+
mode: The proposed validator mode.
|
| 40 |
+
each_item: For complex objects (sets, lists etc.) whether to validate individual
|
| 41 |
+
elements rather than the whole object.
|
| 42 |
+
always: Whether this method and other validators should be called even if the value is missing.
|
| 43 |
+
check_fields: Whether to check that the fields actually exist on the model.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
decorator_repr: ClassVar[str] = '@validator'
|
| 47 |
+
|
| 48 |
+
fields: tuple[str, ...]
|
| 49 |
+
mode: Literal['before', 'after']
|
| 50 |
+
each_item: bool
|
| 51 |
+
always: bool
|
| 52 |
+
check_fields: bool | None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(**slots_true)
|
| 56 |
+
class FieldValidatorDecoratorInfo:
|
| 57 |
+
"""A container for data from `@field_validator` so that we can access it
|
| 58 |
+
while building the pydantic-core schema.
|
| 59 |
+
|
| 60 |
+
Attributes:
|
| 61 |
+
decorator_repr: A class variable representing the decorator string, '@field_validator'.
|
| 62 |
+
fields: A tuple of field names the validator should be called on.
|
| 63 |
+
mode: The proposed validator mode.
|
| 64 |
+
check_fields: Whether to check that the fields actually exist on the model.
|
| 65 |
+
json_schema_input_type: The input type of the function. This is only used to generate
|
| 66 |
+
the appropriate JSON Schema (in validation mode) and can only specified
|
| 67 |
+
when `mode` is either `'before'`, `'plain'` or `'wrap'`.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
decorator_repr: ClassVar[str] = '@field_validator'
|
| 71 |
+
|
| 72 |
+
fields: tuple[str, ...]
|
| 73 |
+
mode: FieldValidatorModes
|
| 74 |
+
check_fields: bool | None
|
| 75 |
+
json_schema_input_type: Any
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(**slots_true)
|
| 79 |
+
class RootValidatorDecoratorInfo:
|
| 80 |
+
"""A container for data from `@root_validator` so that we can access it
|
| 81 |
+
while building the pydantic-core schema.
|
| 82 |
+
|
| 83 |
+
Attributes:
|
| 84 |
+
decorator_repr: A class variable representing the decorator string, '@root_validator'.
|
| 85 |
+
mode: The proposed validator mode.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
decorator_repr: ClassVar[str] = '@root_validator'
|
| 89 |
+
mode: Literal['before', 'after']
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass(**slots_true)
|
| 93 |
+
class FieldSerializerDecoratorInfo:
|
| 94 |
+
"""A container for data from `@field_serializer` so that we can access it
|
| 95 |
+
while building the pydantic-core schema.
|
| 96 |
+
|
| 97 |
+
Attributes:
|
| 98 |
+
decorator_repr: A class variable representing the decorator string, '@field_serializer'.
|
| 99 |
+
fields: A tuple of field names the serializer should be called on.
|
| 100 |
+
mode: The proposed serializer mode.
|
| 101 |
+
return_type: The type of the serializer's return value.
|
| 102 |
+
when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`,
|
| 103 |
+
and `'json-unless-none'`.
|
| 104 |
+
check_fields: Whether to check that the fields actually exist on the model.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
decorator_repr: ClassVar[str] = '@field_serializer'
|
| 108 |
+
fields: tuple[str, ...]
|
| 109 |
+
mode: Literal['plain', 'wrap']
|
| 110 |
+
return_type: Any
|
| 111 |
+
when_used: core_schema.WhenUsed
|
| 112 |
+
check_fields: bool | None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclass(**slots_true)
|
| 116 |
+
class ModelSerializerDecoratorInfo:
|
| 117 |
+
"""A container for data from `@model_serializer` so that we can access it
|
| 118 |
+
while building the pydantic-core schema.
|
| 119 |
+
|
| 120 |
+
Attributes:
|
| 121 |
+
decorator_repr: A class variable representing the decorator string, '@model_serializer'.
|
| 122 |
+
mode: The proposed serializer mode.
|
| 123 |
+
return_type: The type of the serializer's return value.
|
| 124 |
+
when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`,
|
| 125 |
+
and `'json-unless-none'`.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
decorator_repr: ClassVar[str] = '@model_serializer'
|
| 129 |
+
mode: Literal['plain', 'wrap']
|
| 130 |
+
return_type: Any
|
| 131 |
+
when_used: core_schema.WhenUsed
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass(**slots_true)
|
| 135 |
+
class ModelValidatorDecoratorInfo:
|
| 136 |
+
"""A container for data from `@model_validator` so that we can access it
|
| 137 |
+
while building the pydantic-core schema.
|
| 138 |
+
|
| 139 |
+
Attributes:
|
| 140 |
+
decorator_repr: A class variable representing the decorator string, '@model_validator'.
|
| 141 |
+
mode: The proposed serializer mode.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
decorator_repr: ClassVar[str] = '@model_validator'
|
| 145 |
+
mode: Literal['wrap', 'before', 'after']
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
DecoratorInfo: TypeAlias = """Union[
|
| 149 |
+
ValidatorDecoratorInfo,
|
| 150 |
+
FieldValidatorDecoratorInfo,
|
| 151 |
+
RootValidatorDecoratorInfo,
|
| 152 |
+
FieldSerializerDecoratorInfo,
|
| 153 |
+
ModelSerializerDecoratorInfo,
|
| 154 |
+
ModelValidatorDecoratorInfo,
|
| 155 |
+
ComputedFieldInfo,
|
| 156 |
+
]"""
|
| 157 |
+
|
| 158 |
+
ReturnType = TypeVar('ReturnType')
|
| 159 |
+
DecoratedType: TypeAlias = (
|
| 160 |
+
'Union[classmethod[Any, Any, ReturnType], staticmethod[Any, ReturnType], Callable[..., ReturnType], property]'
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass # can't use slots here since we set attributes on `__post_init__`
|
| 165 |
+
class PydanticDescriptorProxy(Generic[ReturnType]):
|
| 166 |
+
"""Wrap a classmethod, staticmethod, property or unbound function
|
| 167 |
+
and act as a descriptor that allows us to detect decorated items
|
| 168 |
+
from the class' attributes.
|
| 169 |
+
|
| 170 |
+
This class' __get__ returns the wrapped item's __get__ result,
|
| 171 |
+
which makes it transparent for classmethods and staticmethods.
|
| 172 |
+
|
| 173 |
+
Attributes:
|
| 174 |
+
wrapped: The decorator that has to be wrapped.
|
| 175 |
+
decorator_info: The decorator info.
|
| 176 |
+
shim: A wrapper function to wrap V1 style function.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
wrapped: DecoratedType[ReturnType]
|
| 180 |
+
decorator_info: DecoratorInfo
|
| 181 |
+
shim: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None
|
| 182 |
+
|
| 183 |
+
def __post_init__(self):
|
| 184 |
+
for attr in 'setter', 'deleter':
|
| 185 |
+
if hasattr(self.wrapped, attr):
|
| 186 |
+
f = partial(self._call_wrapped_attr, name=attr)
|
| 187 |
+
setattr(self, attr, f)
|
| 188 |
+
|
| 189 |
+
def _call_wrapped_attr(self, func: Callable[[Any], None], *, name: str) -> PydanticDescriptorProxy[ReturnType]:
|
| 190 |
+
self.wrapped = getattr(self.wrapped, name)(func)
|
| 191 |
+
if isinstance(self.wrapped, property):
|
| 192 |
+
# update ComputedFieldInfo.wrapped_property
|
| 193 |
+
from ..fields import ComputedFieldInfo
|
| 194 |
+
|
| 195 |
+
if isinstance(self.decorator_info, ComputedFieldInfo):
|
| 196 |
+
self.decorator_info.wrapped_property = self.wrapped
|
| 197 |
+
return self
|
| 198 |
+
|
| 199 |
+
def __get__(self, obj: object | None, obj_type: type[object] | None = None) -> PydanticDescriptorProxy[ReturnType]:
|
| 200 |
+
try:
|
| 201 |
+
return self.wrapped.__get__(obj, obj_type) # pyright: ignore[reportReturnType]
|
| 202 |
+
except AttributeError:
|
| 203 |
+
# not a descriptor, e.g. a partial object
|
| 204 |
+
return self.wrapped # type: ignore[return-value]
|
| 205 |
+
|
| 206 |
+
def __set_name__(self, instance: Any, name: str) -> None:
|
| 207 |
+
if hasattr(self.wrapped, '__set_name__'):
|
| 208 |
+
self.wrapped.__set_name__(instance, name) # pyright: ignore[reportFunctionMemberAccess]
|
| 209 |
+
|
| 210 |
+
def __getattr__(self, name: str, /) -> Any:
|
| 211 |
+
"""Forward checks for __isabstractmethod__ and such."""
|
| 212 |
+
return getattr(self.wrapped, name)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
DecoratorInfoType = TypeVar('DecoratorInfoType', bound=DecoratorInfo)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@dataclass(**slots_true)
|
| 219 |
+
class Decorator(Generic[DecoratorInfoType]):
|
| 220 |
+
"""A generic container class to join together the decorator metadata
|
| 221 |
+
(metadata from decorator itself, which we have when the
|
| 222 |
+
decorator is called but not when we are building the core-schema)
|
| 223 |
+
and the bound function (which we have after the class itself is created).
|
| 224 |
+
|
| 225 |
+
Attributes:
|
| 226 |
+
cls_ref: The class ref.
|
| 227 |
+
cls_var_name: The decorated function name.
|
| 228 |
+
func: The decorated function.
|
| 229 |
+
shim: A wrapper function to wrap V1 style function.
|
| 230 |
+
info: The decorator info.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
cls_ref: str
|
| 234 |
+
cls_var_name: str
|
| 235 |
+
func: Callable[..., Any]
|
| 236 |
+
shim: Callable[[Any], Any] | None
|
| 237 |
+
info: DecoratorInfoType
|
| 238 |
+
|
| 239 |
+
@staticmethod
|
| 240 |
+
def build(
|
| 241 |
+
cls_: Any,
|
| 242 |
+
*,
|
| 243 |
+
cls_var_name: str,
|
| 244 |
+
shim: Callable[[Any], Any] | None,
|
| 245 |
+
info: DecoratorInfoType,
|
| 246 |
+
) -> Decorator[DecoratorInfoType]:
|
| 247 |
+
"""Build a new decorator.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
cls_: The class.
|
| 251 |
+
cls_var_name: The decorated function name.
|
| 252 |
+
shim: A wrapper function to wrap V1 style function.
|
| 253 |
+
info: The decorator info.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
The new decorator instance.
|
| 257 |
+
"""
|
| 258 |
+
func = get_attribute_from_bases(cls_, cls_var_name)
|
| 259 |
+
if shim is not None:
|
| 260 |
+
func = shim(func)
|
| 261 |
+
func = unwrap_wrapped_function(func, unwrap_partial=False)
|
| 262 |
+
if not callable(func):
|
| 263 |
+
# This branch will get hit for classmethod properties
|
| 264 |
+
attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__`
|
| 265 |
+
if isinstance(attribute, PydanticDescriptorProxy):
|
| 266 |
+
func = unwrap_wrapped_function(attribute.wrapped)
|
| 267 |
+
return Decorator(
|
| 268 |
+
cls_ref=get_type_ref(cls_),
|
| 269 |
+
cls_var_name=cls_var_name,
|
| 270 |
+
func=func,
|
| 271 |
+
shim=shim,
|
| 272 |
+
info=info,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
def bind_to_cls(self, cls: Any) -> Decorator[DecoratorInfoType]:
|
| 276 |
+
"""Bind the decorator to a class.
|
| 277 |
+
|
| 278 |
+
Args:
|
| 279 |
+
cls: the class.
|
| 280 |
+
|
| 281 |
+
Returns:
|
| 282 |
+
The new decorator instance.
|
| 283 |
+
"""
|
| 284 |
+
return self.build(
|
| 285 |
+
cls,
|
| 286 |
+
cls_var_name=self.cls_var_name,
|
| 287 |
+
shim=self.shim,
|
| 288 |
+
info=self.info,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def get_bases(tp: type[Any]) -> tuple[type[Any], ...]:
|
| 293 |
+
"""Get the base classes of a class or typeddict.
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
tp: The type or class to get the bases.
|
| 297 |
+
|
| 298 |
+
Returns:
|
| 299 |
+
The base classes.
|
| 300 |
+
"""
|
| 301 |
+
if is_typeddict(tp):
|
| 302 |
+
return tp.__orig_bases__ # type: ignore
|
| 303 |
+
try:
|
| 304 |
+
return tp.__bases__
|
| 305 |
+
except AttributeError:
|
| 306 |
+
return ()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def mro(tp: type[Any]) -> tuple[type[Any], ...]:
|
| 310 |
+
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
|
| 311 |
+
|
| 312 |
+
See https://www.python.org/download/releases/2.3/mro/
|
| 313 |
+
"""
|
| 314 |
+
# try to use the existing mro, for performance mainly
|
| 315 |
+
# but also because it helps verify the implementation below
|
| 316 |
+
if not is_typeddict(tp):
|
| 317 |
+
try:
|
| 318 |
+
return tp.__mro__
|
| 319 |
+
except AttributeError:
|
| 320 |
+
# GenericAlias and some other cases
|
| 321 |
+
pass
|
| 322 |
+
|
| 323 |
+
bases = get_bases(tp)
|
| 324 |
+
return (tp,) + mro_for_bases(bases)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]:
|
| 328 |
+
def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]:
|
| 329 |
+
while True:
|
| 330 |
+
non_empty = [seq for seq in seqs if seq]
|
| 331 |
+
if not non_empty:
|
| 332 |
+
# Nothing left to process, we're done.
|
| 333 |
+
return
|
| 334 |
+
candidate: type[Any] | None = None
|
| 335 |
+
for seq in non_empty: # Find merge candidates among seq heads.
|
| 336 |
+
candidate = seq[0]
|
| 337 |
+
not_head = [s for s in non_empty if candidate in islice(s, 1, None)]
|
| 338 |
+
if not_head:
|
| 339 |
+
# Reject the candidate.
|
| 340 |
+
candidate = None
|
| 341 |
+
else:
|
| 342 |
+
break
|
| 343 |
+
if not candidate:
|
| 344 |
+
raise TypeError('Inconsistent hierarchy, no C3 MRO is possible')
|
| 345 |
+
yield candidate
|
| 346 |
+
for seq in non_empty:
|
| 347 |
+
# Remove candidate.
|
| 348 |
+
if seq[0] == candidate:
|
| 349 |
+
seq.popleft()
|
| 350 |
+
|
| 351 |
+
seqs = [deque(mro(base)) for base in bases] + [deque(bases)]
|
| 352 |
+
return tuple(merge_seqs(seqs))
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
_sentinel = object()
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any:
|
| 359 |
+
"""Get the attribute from the next class in the MRO that has it,
|
| 360 |
+
aiming to simulate calling the method on the actual class.
|
| 361 |
+
|
| 362 |
+
The reason for iterating over the mro instead of just getting
|
| 363 |
+
the attribute (which would do that for us) is to support TypedDict,
|
| 364 |
+
which lacks a real __mro__, but can have a virtual one constructed
|
| 365 |
+
from its bases (as done here).
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes.
|
| 369 |
+
name: The name of the attribute to retrieve.
|
| 370 |
+
|
| 371 |
+
Returns:
|
| 372 |
+
Any: The attribute value, if found.
|
| 373 |
+
|
| 374 |
+
Raises:
|
| 375 |
+
AttributeError: If the attribute is not found in any class in the MRO.
|
| 376 |
+
"""
|
| 377 |
+
if isinstance(tp, tuple):
|
| 378 |
+
for base in mro_for_bases(tp):
|
| 379 |
+
attribute = base.__dict__.get(name, _sentinel)
|
| 380 |
+
if attribute is not _sentinel:
|
| 381 |
+
attribute_get = getattr(attribute, '__get__', None)
|
| 382 |
+
if attribute_get is not None:
|
| 383 |
+
return attribute_get(None, tp)
|
| 384 |
+
return attribute
|
| 385 |
+
raise AttributeError(f'{name} not found in {tp}')
|
| 386 |
+
else:
|
| 387 |
+
try:
|
| 388 |
+
return getattr(tp, name)
|
| 389 |
+
except AttributeError:
|
| 390 |
+
return get_attribute_from_bases(mro(tp), name)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any:
|
| 394 |
+
"""Get an attribute out of the `__dict__` following the MRO.
|
| 395 |
+
This prevents the call to `__get__` on the descriptor, and allows
|
| 396 |
+
us to get the original function for classmethod properties.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
tp: The type or class to search for the attribute.
|
| 400 |
+
name: The name of the attribute to retrieve.
|
| 401 |
+
|
| 402 |
+
Returns:
|
| 403 |
+
Any: The attribute value, if found.
|
| 404 |
+
|
| 405 |
+
Raises:
|
| 406 |
+
KeyError: If the attribute is not found in any class's `__dict__` in the MRO.
|
| 407 |
+
"""
|
| 408 |
+
for base in reversed(mro(tp)):
|
| 409 |
+
if name in base.__dict__:
|
| 410 |
+
return base.__dict__[name]
|
| 411 |
+
return tp.__dict__[name] # raise the error
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
@dataclass(**slots_true)
|
| 415 |
+
class DecoratorInfos:
|
| 416 |
+
"""Mapping of name in the class namespace to decorator info.
|
| 417 |
+
|
| 418 |
+
note that the name in the class namespace is the function or attribute name
|
| 419 |
+
not the field name!
|
| 420 |
+
"""
|
| 421 |
+
|
| 422 |
+
validators: dict[str, Decorator[ValidatorDecoratorInfo]] = field(default_factory=dict)
|
| 423 |
+
field_validators: dict[str, Decorator[FieldValidatorDecoratorInfo]] = field(default_factory=dict)
|
| 424 |
+
root_validators: dict[str, Decorator[RootValidatorDecoratorInfo]] = field(default_factory=dict)
|
| 425 |
+
field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]] = field(default_factory=dict)
|
| 426 |
+
model_serializers: dict[str, Decorator[ModelSerializerDecoratorInfo]] = field(default_factory=dict)
|
| 427 |
+
model_validators: dict[str, Decorator[ModelValidatorDecoratorInfo]] = field(default_factory=dict)
|
| 428 |
+
computed_fields: dict[str, Decorator[ComputedFieldInfo]] = field(default_factory=dict)
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def build(model_dc: type[Any]) -> DecoratorInfos: # noqa: C901 (ignore complexity)
|
| 432 |
+
"""We want to collect all DecFunc instances that exist as
|
| 433 |
+
attributes in the namespace of the class (a BaseModel or dataclass)
|
| 434 |
+
that called us
|
| 435 |
+
But we want to collect these in the order of the bases
|
| 436 |
+
So instead of getting them all from the leaf class (the class that called us),
|
| 437 |
+
we traverse the bases from root (the oldest ancestor class) to leaf
|
| 438 |
+
and collect all of the instances as we go, taking care to replace
|
| 439 |
+
any duplicate ones with the last one we see to mimic how function overriding
|
| 440 |
+
works with inheritance.
|
| 441 |
+
If we do replace any functions we put the replacement into the position
|
| 442 |
+
the replaced function was in; that is, we maintain the order.
|
| 443 |
+
"""
|
| 444 |
+
# reminder: dicts are ordered and replacement does not alter the order
|
| 445 |
+
res = DecoratorInfos()
|
| 446 |
+
for base in reversed(mro(model_dc)[1:]):
|
| 447 |
+
existing: DecoratorInfos | None = base.__dict__.get('__pydantic_decorators__')
|
| 448 |
+
if existing is None:
|
| 449 |
+
existing = DecoratorInfos.build(base)
|
| 450 |
+
res.validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.validators.items()})
|
| 451 |
+
res.field_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_validators.items()})
|
| 452 |
+
res.root_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.root_validators.items()})
|
| 453 |
+
res.field_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_serializers.items()})
|
| 454 |
+
res.model_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_serializers.items()})
|
| 455 |
+
res.model_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_validators.items()})
|
| 456 |
+
res.computed_fields.update({k: v.bind_to_cls(model_dc) for k, v in existing.computed_fields.items()})
|
| 457 |
+
|
| 458 |
+
to_replace: list[tuple[str, Any]] = []
|
| 459 |
+
|
| 460 |
+
for var_name, var_value in vars(model_dc).items():
|
| 461 |
+
if isinstance(var_value, PydanticDescriptorProxy):
|
| 462 |
+
info = var_value.decorator_info
|
| 463 |
+
if isinstance(info, ValidatorDecoratorInfo):
|
| 464 |
+
res.validators[var_name] = Decorator.build(
|
| 465 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 466 |
+
)
|
| 467 |
+
elif isinstance(info, FieldValidatorDecoratorInfo):
|
| 468 |
+
res.field_validators[var_name] = Decorator.build(
|
| 469 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 470 |
+
)
|
| 471 |
+
elif isinstance(info, RootValidatorDecoratorInfo):
|
| 472 |
+
res.root_validators[var_name] = Decorator.build(
|
| 473 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 474 |
+
)
|
| 475 |
+
elif isinstance(info, FieldSerializerDecoratorInfo):
|
| 476 |
+
# check whether a serializer function is already registered for fields
|
| 477 |
+
for field_serializer_decorator in res.field_serializers.values():
|
| 478 |
+
# check that each field has at most one serializer function.
|
| 479 |
+
# serializer functions for the same field in subclasses are allowed,
|
| 480 |
+
# and are treated as overrides
|
| 481 |
+
if field_serializer_decorator.cls_var_name == var_name:
|
| 482 |
+
continue
|
| 483 |
+
for f in info.fields:
|
| 484 |
+
if f in field_serializer_decorator.info.fields:
|
| 485 |
+
raise PydanticUserError(
|
| 486 |
+
'Multiple field serializer functions were defined '
|
| 487 |
+
f'for field {f!r}, this is not allowed.',
|
| 488 |
+
code='multiple-field-serializers',
|
| 489 |
+
)
|
| 490 |
+
res.field_serializers[var_name] = Decorator.build(
|
| 491 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 492 |
+
)
|
| 493 |
+
elif isinstance(info, ModelValidatorDecoratorInfo):
|
| 494 |
+
res.model_validators[var_name] = Decorator.build(
|
| 495 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 496 |
+
)
|
| 497 |
+
elif isinstance(info, ModelSerializerDecoratorInfo):
|
| 498 |
+
res.model_serializers[var_name] = Decorator.build(
|
| 499 |
+
model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
|
| 500 |
+
)
|
| 501 |
+
else:
|
| 502 |
+
from ..fields import ComputedFieldInfo
|
| 503 |
+
|
| 504 |
+
isinstance(var_value, ComputedFieldInfo)
|
| 505 |
+
res.computed_fields[var_name] = Decorator.build(
|
| 506 |
+
model_dc, cls_var_name=var_name, shim=None, info=info
|
| 507 |
+
)
|
| 508 |
+
to_replace.append((var_name, var_value.wrapped))
|
| 509 |
+
if to_replace:
|
| 510 |
+
# If we can save `__pydantic_decorators__` on the class we'll be able to check for it above
|
| 511 |
+
# so then we don't need to re-process the type, which means we can discard our descriptor wrappers
|
| 512 |
+
# and replace them with the thing they are wrapping (see the other setattr call below)
|
| 513 |
+
# which allows validator class methods to also function as regular class methods
|
| 514 |
+
model_dc.__pydantic_decorators__ = res
|
| 515 |
+
for name, value in to_replace:
|
| 516 |
+
setattr(model_dc, name, value)
|
| 517 |
+
return res
|
| 518 |
+
|
| 519 |
+
def update_from_config(self, config_wrapper: ConfigWrapper) -> None:
|
| 520 |
+
"""Update the decorator infos from the configuration of the class they are attached to."""
|
| 521 |
+
for name, computed_field_dec in self.computed_fields.items():
|
| 522 |
+
computed_field_dec.info._update_from_config(config_wrapper, name)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def inspect_validator(
|
| 526 |
+
validator: Callable[..., Any], *, mode: FieldValidatorModes, type: Literal['field', 'model']
|
| 527 |
+
) -> bool:
|
| 528 |
+
"""Look at a field or model validator function and determine whether it takes an info argument.
|
| 529 |
+
|
| 530 |
+
An error is raised if the function has an invalid signature.
|
| 531 |
+
|
| 532 |
+
Args:
|
| 533 |
+
validator: The validator function to inspect.
|
| 534 |
+
mode: The proposed validator mode.
|
| 535 |
+
type: The type of validator, either 'field' or 'model'.
|
| 536 |
+
|
| 537 |
+
Returns:
|
| 538 |
+
Whether the validator takes an info argument.
|
| 539 |
+
"""
|
| 540 |
+
try:
|
| 541 |
+
sig = _signature_no_eval(validator)
|
| 542 |
+
except (ValueError, TypeError):
|
| 543 |
+
# `inspect.signature` might not be able to infer a signature, e.g. with C objects.
|
| 544 |
+
# In this case, we assume no info argument is present:
|
| 545 |
+
return False
|
| 546 |
+
n_positional = count_positional_required_params(sig)
|
| 547 |
+
if mode == 'wrap':
|
| 548 |
+
if n_positional == 3:
|
| 549 |
+
return True
|
| 550 |
+
elif n_positional == 2:
|
| 551 |
+
return False
|
| 552 |
+
else:
|
| 553 |
+
assert mode in {'before', 'after', 'plain'}, f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain"
|
| 554 |
+
if n_positional == 2:
|
| 555 |
+
return True
|
| 556 |
+
elif n_positional == 1:
|
| 557 |
+
return False
|
| 558 |
+
|
| 559 |
+
raise PydanticUserError(
|
| 560 |
+
f'Unrecognized {type} validator function signature for {validator} with `mode={mode}`: {sig}',
|
| 561 |
+
code='validator-signature',
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def inspect_field_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> tuple[bool, bool]:
|
| 566 |
+
"""Look at a field serializer function and determine if it is a field serializer,
|
| 567 |
+
and whether it takes an info argument.
|
| 568 |
+
|
| 569 |
+
An error is raised if the function has an invalid signature.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
serializer: The serializer function to inspect.
|
| 573 |
+
mode: The serializer mode, either 'plain' or 'wrap'.
|
| 574 |
+
|
| 575 |
+
Returns:
|
| 576 |
+
Tuple of (is_field_serializer, info_arg).
|
| 577 |
+
"""
|
| 578 |
+
try:
|
| 579 |
+
sig = _signature_no_eval(serializer)
|
| 580 |
+
except (ValueError, TypeError):
|
| 581 |
+
# `inspect.signature` might not be able to infer a signature, e.g. with C objects.
|
| 582 |
+
# In this case, we assume no info argument is present and this is not a method:
|
| 583 |
+
return (False, False)
|
| 584 |
+
|
| 585 |
+
first = next(iter(sig.parameters.values()), None)
|
| 586 |
+
is_field_serializer = first is not None and first.name == 'self'
|
| 587 |
+
|
| 588 |
+
n_positional = count_positional_required_params(sig)
|
| 589 |
+
if is_field_serializer:
|
| 590 |
+
# -1 to correct for self parameter
|
| 591 |
+
info_arg = _serializer_info_arg(mode, n_positional - 1)
|
| 592 |
+
else:
|
| 593 |
+
info_arg = _serializer_info_arg(mode, n_positional)
|
| 594 |
+
|
| 595 |
+
if info_arg is None:
|
| 596 |
+
raise PydanticUserError(
|
| 597 |
+
f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
|
| 598 |
+
code='field-serializer-signature',
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
return is_field_serializer, info_arg
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def inspect_annotated_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
|
| 605 |
+
"""Look at a serializer function used via `Annotated` and determine whether it takes an info argument.
|
| 606 |
+
|
| 607 |
+
An error is raised if the function has an invalid signature.
|
| 608 |
+
|
| 609 |
+
Args:
|
| 610 |
+
serializer: The serializer function to check.
|
| 611 |
+
mode: The serializer mode, either 'plain' or 'wrap'.
|
| 612 |
+
|
| 613 |
+
Returns:
|
| 614 |
+
info_arg
|
| 615 |
+
"""
|
| 616 |
+
try:
|
| 617 |
+
sig = _signature_no_eval(serializer)
|
| 618 |
+
except (ValueError, TypeError):
|
| 619 |
+
# `inspect.signature` might not be able to infer a signature, e.g. with C objects.
|
| 620 |
+
# In this case, we assume no info argument is present:
|
| 621 |
+
return False
|
| 622 |
+
info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
|
| 623 |
+
if info_arg is None:
|
| 624 |
+
raise PydanticUserError(
|
| 625 |
+
f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
|
| 626 |
+
code='field-serializer-signature',
|
| 627 |
+
)
|
| 628 |
+
else:
|
| 629 |
+
return info_arg
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
|
| 633 |
+
"""Look at a model serializer function and determine whether it takes an info argument.
|
| 634 |
+
|
| 635 |
+
An error is raised if the function has an invalid signature.
|
| 636 |
+
|
| 637 |
+
Args:
|
| 638 |
+
serializer: The serializer function to check.
|
| 639 |
+
mode: The serializer mode, either 'plain' or 'wrap'.
|
| 640 |
+
|
| 641 |
+
Returns:
|
| 642 |
+
`info_arg` - whether the function expects an info argument.
|
| 643 |
+
"""
|
| 644 |
+
if isinstance(serializer, (staticmethod, classmethod)) or not is_instance_method_from_sig(serializer):
|
| 645 |
+
raise PydanticUserError(
|
| 646 |
+
'`@model_serializer` must be applied to instance methods', code='model-serializer-instance-method'
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
sig = _signature_no_eval(serializer)
|
| 650 |
+
info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
|
| 651 |
+
if info_arg is None:
|
| 652 |
+
raise PydanticUserError(
|
| 653 |
+
f'Unrecognized model_serializer function signature for {serializer} with `mode={mode}`:{sig}',
|
| 654 |
+
code='model-serializer-signature',
|
| 655 |
+
)
|
| 656 |
+
else:
|
| 657 |
+
return info_arg
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None:
|
| 661 |
+
if mode == 'plain':
|
| 662 |
+
if n_positional == 1:
|
| 663 |
+
# (input_value: Any, /) -> Any
|
| 664 |
+
return False
|
| 665 |
+
elif n_positional == 2:
|
| 666 |
+
# (model: Any, input_value: Any, /) -> Any
|
| 667 |
+
return True
|
| 668 |
+
else:
|
| 669 |
+
assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'"
|
| 670 |
+
if n_positional == 2:
|
| 671 |
+
# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
|
| 672 |
+
return False
|
| 673 |
+
elif n_positional == 3:
|
| 674 |
+
# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
|
| 675 |
+
return True
|
| 676 |
+
|
| 677 |
+
return None
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
AnyDecoratorCallable: TypeAlias = (
|
| 681 |
+
'Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any], Callable[..., Any]]'
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def is_instance_method_from_sig(function: AnyDecoratorCallable) -> bool:
|
| 686 |
+
"""Whether the function is an instance method.
|
| 687 |
+
|
| 688 |
+
It will consider a function as instance method if the first parameter of
|
| 689 |
+
function is `self`.
|
| 690 |
+
|
| 691 |
+
Args:
|
| 692 |
+
function: The function to check.
|
| 693 |
+
|
| 694 |
+
Returns:
|
| 695 |
+
`True` if the function is an instance method, `False` otherwise.
|
| 696 |
+
"""
|
| 697 |
+
sig = _signature_no_eval(unwrap_wrapped_function(function))
|
| 698 |
+
first = next(iter(sig.parameters.values()), None)
|
| 699 |
+
if first and first.name == 'self':
|
| 700 |
+
return True
|
| 701 |
+
return False
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def ensure_classmethod_based_on_signature(function: AnyDecoratorCallable) -> Any:
|
| 705 |
+
"""Apply the `@classmethod` decorator on the function.
|
| 706 |
+
|
| 707 |
+
Args:
|
| 708 |
+
function: The function to apply the decorator on.
|
| 709 |
+
|
| 710 |
+
Return:
|
| 711 |
+
The `@classmethod` decorator applied function.
|
| 712 |
+
"""
|
| 713 |
+
if not isinstance(
|
| 714 |
+
unwrap_wrapped_function(function, unwrap_class_static_method=False), classmethod
|
| 715 |
+
) and _is_classmethod_from_sig(function):
|
| 716 |
+
return classmethod(function) # type: ignore[arg-type]
|
| 717 |
+
return function
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def _is_classmethod_from_sig(function: AnyDecoratorCallable) -> bool:
|
| 721 |
+
sig = _signature_no_eval(unwrap_wrapped_function(function))
|
| 722 |
+
first = next(iter(sig.parameters.values()), None)
|
| 723 |
+
if first and first.name == 'cls':
|
| 724 |
+
return True
|
| 725 |
+
return False
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def unwrap_wrapped_function(
|
| 729 |
+
func: Any,
|
| 730 |
+
*,
|
| 731 |
+
unwrap_partial: bool = True,
|
| 732 |
+
unwrap_class_static_method: bool = True,
|
| 733 |
+
) -> Any:
|
| 734 |
+
"""Recursively unwraps a wrapped function until the underlying function is reached.
|
| 735 |
+
This handles property, functools.partial, functools.partialmethod, staticmethod, and classmethod.
|
| 736 |
+
|
| 737 |
+
Args:
|
| 738 |
+
func: The function to unwrap.
|
| 739 |
+
unwrap_partial: If True (default), unwrap partial and partialmethod decorators.
|
| 740 |
+
unwrap_class_static_method: If True (default), also unwrap classmethod and staticmethod
|
| 741 |
+
decorators. If False, only unwrap partial and partialmethod decorators.
|
| 742 |
+
|
| 743 |
+
Returns:
|
| 744 |
+
The underlying function of the wrapped function.
|
| 745 |
+
"""
|
| 746 |
+
# Define the types we want to check against as a single tuple.
|
| 747 |
+
unwrap_types = (
|
| 748 |
+
(property, cached_property)
|
| 749 |
+
+ ((partial, partialmethod) if unwrap_partial else ())
|
| 750 |
+
+ ((staticmethod, classmethod) if unwrap_class_static_method else ())
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
while isinstance(func, unwrap_types):
|
| 754 |
+
if unwrap_class_static_method and isinstance(func, (classmethod, staticmethod)):
|
| 755 |
+
func = func.__func__
|
| 756 |
+
elif isinstance(func, (partial, partialmethod)):
|
| 757 |
+
func = func.func
|
| 758 |
+
elif isinstance(func, property):
|
| 759 |
+
func = func.fget # arbitrary choice, convenient for computed fields
|
| 760 |
+
else:
|
| 761 |
+
# Make coverage happy as it can only get here in the last possible case
|
| 762 |
+
assert isinstance(func, cached_property)
|
| 763 |
+
func = func.func # type: ignore
|
| 764 |
+
|
| 765 |
+
return func
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
_function_like = (
|
| 769 |
+
partial,
|
| 770 |
+
partialmethod,
|
| 771 |
+
types.FunctionType,
|
| 772 |
+
types.BuiltinFunctionType,
|
| 773 |
+
types.MethodType,
|
| 774 |
+
types.WrapperDescriptorType,
|
| 775 |
+
types.MethodWrapperType,
|
| 776 |
+
types.MemberDescriptorType,
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
def get_callable_return_type(
|
| 781 |
+
callable_obj: Any,
|
| 782 |
+
globalns: GlobalsNamespace | None = None,
|
| 783 |
+
localns: MappingNamespace | None = None,
|
| 784 |
+
) -> Any | PydanticUndefinedType:
|
| 785 |
+
"""Get the callable return type.
|
| 786 |
+
|
| 787 |
+
Args:
|
| 788 |
+
callable_obj: The callable to analyze.
|
| 789 |
+
globalns: The globals namespace to use during type annotation evaluation.
|
| 790 |
+
localns: The locals namespace to use during type annotation evaluation.
|
| 791 |
+
|
| 792 |
+
Returns:
|
| 793 |
+
The function return type.
|
| 794 |
+
"""
|
| 795 |
+
if isinstance(callable_obj, type):
|
| 796 |
+
# types are callables, and we assume the return type
|
| 797 |
+
# is the type itself (e.g. `int()` results in an instance of `int`).
|
| 798 |
+
return callable_obj
|
| 799 |
+
|
| 800 |
+
if not isinstance(callable_obj, _function_like):
|
| 801 |
+
call_func = getattr(type(callable_obj), '__call__', None) # noqa: B004
|
| 802 |
+
if call_func is not None:
|
| 803 |
+
callable_obj = call_func
|
| 804 |
+
|
| 805 |
+
hints = get_function_type_hints(
|
| 806 |
+
unwrap_wrapped_function(callable_obj),
|
| 807 |
+
include_keys={'return'},
|
| 808 |
+
globalns=globalns,
|
| 809 |
+
localns=localns,
|
| 810 |
+
)
|
| 811 |
+
return hints.get('return', PydanticUndefined)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def count_positional_required_params(sig: Signature) -> int:
|
| 815 |
+
"""Get the number of positional (required) arguments of a signature.
|
| 816 |
+
|
| 817 |
+
This function should only be used to inspect signatures of validation and serialization functions.
|
| 818 |
+
The first argument (the value being serialized or validated) is counted as a required argument
|
| 819 |
+
even if a default value exists.
|
| 820 |
+
|
| 821 |
+
Returns:
|
| 822 |
+
The number of positional arguments of a signature.
|
| 823 |
+
"""
|
| 824 |
+
parameters = list(sig.parameters.values())
|
| 825 |
+
return sum(
|
| 826 |
+
1
|
| 827 |
+
for param in parameters
|
| 828 |
+
if can_be_positional(param)
|
| 829 |
+
# First argument is the value being validated/serialized, and can have a default value
|
| 830 |
+
# (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg
|
| 831 |
+
# for instance) should be required, and thus without any default value.
|
| 832 |
+
and (param.default is Parameter.empty or param is parameters[0])
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def ensure_property(f: Any) -> Any:
|
| 837 |
+
"""Ensure that a function is a `property` or `cached_property`, or is a valid descriptor.
|
| 838 |
+
|
| 839 |
+
Args:
|
| 840 |
+
f: The function to check.
|
| 841 |
+
|
| 842 |
+
Returns:
|
| 843 |
+
The function, or a `property` or `cached_property` instance wrapping the function.
|
| 844 |
+
"""
|
| 845 |
+
if ismethoddescriptor(f) or isdatadescriptor(f):
|
| 846 |
+
return f
|
| 847 |
+
else:
|
| 848 |
+
return property(f)
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def _signature_no_eval(f: Callable[..., Any]) -> Signature:
|
| 852 |
+
"""Get the signature of a callable without evaluating any annotations."""
|
| 853 |
+
if sys.version_info >= (3, 14):
|
| 854 |
+
from annotationlib import Format
|
| 855 |
+
|
| 856 |
+
return signature(f, annotation_format=Format.FORWARDREF)
|
| 857 |
+
else:
|
| 858 |
+
return signature(f)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_decorators_v1.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logic for V1 validators, e.g. `@validator` and `@root_validator`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from inspect import Parameter, signature
|
| 6 |
+
from typing import Any, Union, cast
|
| 7 |
+
|
| 8 |
+
from pydantic_core import core_schema
|
| 9 |
+
from typing_extensions import Protocol
|
| 10 |
+
|
| 11 |
+
from ..errors import PydanticUserError
|
| 12 |
+
from ._utils import can_be_positional
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class V1OnlyValueValidator(Protocol):
|
| 16 |
+
"""A simple validator, supported for V1 validators and V2 validators."""
|
| 17 |
+
|
| 18 |
+
def __call__(self, __value: Any) -> Any: ...
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class V1ValidatorWithValues(Protocol):
|
| 22 |
+
"""A validator with `values` argument, supported for V1 validators and V2 validators."""
|
| 23 |
+
|
| 24 |
+
def __call__(self, __value: Any, values: dict[str, Any]) -> Any: ...
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class V1ValidatorWithValuesKwOnly(Protocol):
|
| 28 |
+
"""A validator with keyword only `values` argument, supported for V1 validators and V2 validators."""
|
| 29 |
+
|
| 30 |
+
def __call__(self, __value: Any, *, values: dict[str, Any]) -> Any: ...
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class V1ValidatorWithKwargs(Protocol):
|
| 34 |
+
"""A validator with `kwargs` argument, supported for V1 validators and V2 validators."""
|
| 35 |
+
|
| 36 |
+
def __call__(self, __value: Any, **kwargs: Any) -> Any: ...
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class V1ValidatorWithValuesAndKwargs(Protocol):
|
| 40 |
+
"""A validator with `values` and `kwargs` arguments, supported for V1 validators and V2 validators."""
|
| 41 |
+
|
| 42 |
+
def __call__(self, __value: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
V1Validator = Union[
|
| 46 |
+
V1ValidatorWithValues, V1ValidatorWithValuesKwOnly, V1ValidatorWithKwargs, V1ValidatorWithValuesAndKwargs
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def can_be_keyword(param: Parameter) -> bool:
|
| 51 |
+
return param.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def make_generic_v1_field_validator(validator: V1Validator) -> core_schema.WithInfoValidatorFunction:
|
| 55 |
+
"""Wrap a V1 style field validator for V2 compatibility.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
validator: The V1 style field validator.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
A wrapped V2 style field validator.
|
| 62 |
+
|
| 63 |
+
Raises:
|
| 64 |
+
PydanticUserError: If the signature is not supported or the parameters are
|
| 65 |
+
not available in Pydantic V2.
|
| 66 |
+
"""
|
| 67 |
+
sig = signature(validator)
|
| 68 |
+
|
| 69 |
+
needs_values_kw = False
|
| 70 |
+
|
| 71 |
+
for param_num, (param_name, parameter) in enumerate(sig.parameters.items()):
|
| 72 |
+
if can_be_keyword(parameter) and param_name in ('field', 'config'):
|
| 73 |
+
raise PydanticUserError(
|
| 74 |
+
'The `field` and `config` parameters are not available in Pydantic V2, '
|
| 75 |
+
'please use the `info` parameter instead.',
|
| 76 |
+
code='validator-field-config-info',
|
| 77 |
+
)
|
| 78 |
+
if parameter.kind is Parameter.VAR_KEYWORD:
|
| 79 |
+
needs_values_kw = True
|
| 80 |
+
elif can_be_keyword(parameter) and param_name == 'values':
|
| 81 |
+
needs_values_kw = True
|
| 82 |
+
elif can_be_positional(parameter) and param_num == 0:
|
| 83 |
+
# value
|
| 84 |
+
continue
|
| 85 |
+
elif parameter.default is Parameter.empty: # ignore params with defaults e.g. bound by functools.partial
|
| 86 |
+
raise PydanticUserError(
|
| 87 |
+
f'Unsupported signature for V1 style validator {validator}: {sig} is not supported.',
|
| 88 |
+
code='validator-v1-signature',
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
if needs_values_kw:
|
| 92 |
+
# (v, **kwargs), (v, values, **kwargs), (v, *, values, **kwargs) or (v, *, values)
|
| 93 |
+
val1 = cast(V1ValidatorWithValues, validator)
|
| 94 |
+
|
| 95 |
+
def wrapper1(value: Any, info: core_schema.ValidationInfo) -> Any:
|
| 96 |
+
return val1(value, values=info.data)
|
| 97 |
+
|
| 98 |
+
return wrapper1
|
| 99 |
+
else:
|
| 100 |
+
val2 = cast(V1OnlyValueValidator, validator)
|
| 101 |
+
|
| 102 |
+
def wrapper2(value: Any, _: core_schema.ValidationInfo) -> Any:
|
| 103 |
+
return val2(value)
|
| 104 |
+
|
| 105 |
+
return wrapper2
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
RootValidatorValues = dict[str, Any]
|
| 109 |
+
# technically tuple[model_dict, model_extra, fields_set] | tuple[dataclass_dict, init_vars]
|
| 110 |
+
RootValidatorFieldsTuple = tuple[Any, ...]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class V1RootValidatorFunction(Protocol):
|
| 114 |
+
"""A simple root validator, supported for V1 validators and V2 validators."""
|
| 115 |
+
|
| 116 |
+
def __call__(self, __values: RootValidatorValues) -> RootValidatorValues: ...
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class V2CoreBeforeRootValidator(Protocol):
|
| 120 |
+
"""V2 validator with mode='before'."""
|
| 121 |
+
|
| 122 |
+
def __call__(self, __values: RootValidatorValues, __info: core_schema.ValidationInfo) -> RootValidatorValues: ...
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class V2CoreAfterRootValidator(Protocol):
|
| 126 |
+
"""V2 validator with mode='after'."""
|
| 127 |
+
|
| 128 |
+
def __call__(
|
| 129 |
+
self, __fields_tuple: RootValidatorFieldsTuple, __info: core_schema.ValidationInfo
|
| 130 |
+
) -> RootValidatorFieldsTuple: ...
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_v1_generic_root_validator(
|
| 134 |
+
validator: V1RootValidatorFunction, pre: bool
|
| 135 |
+
) -> V2CoreBeforeRootValidator | V2CoreAfterRootValidator:
|
| 136 |
+
"""Wrap a V1 style root validator for V2 compatibility.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
validator: The V1 style field validator.
|
| 140 |
+
pre: Whether the validator is a pre validator.
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
A wrapped V2 style validator.
|
| 144 |
+
"""
|
| 145 |
+
if pre is True:
|
| 146 |
+
# mode='before' for pydantic-core
|
| 147 |
+
def _wrapper1(values: RootValidatorValues, _: core_schema.ValidationInfo) -> RootValidatorValues:
|
| 148 |
+
return validator(values)
|
| 149 |
+
|
| 150 |
+
return _wrapper1
|
| 151 |
+
|
| 152 |
+
# mode='after' for pydantic-core
|
| 153 |
+
def _wrapper2(fields_tuple: RootValidatorFieldsTuple, _: core_schema.ValidationInfo) -> RootValidatorFieldsTuple:
|
| 154 |
+
if len(fields_tuple) == 2:
|
| 155 |
+
# dataclass, this is easy
|
| 156 |
+
values, init_vars = fields_tuple
|
| 157 |
+
values = validator(values)
|
| 158 |
+
return values, init_vars
|
| 159 |
+
else:
|
| 160 |
+
# ugly hack: to match v1 behaviour, we merge values and model_extra, then split them up based on fields
|
| 161 |
+
# afterwards
|
| 162 |
+
model_dict, model_extra, fields_set = fields_tuple
|
| 163 |
+
if model_extra:
|
| 164 |
+
fields = set(model_dict.keys())
|
| 165 |
+
model_dict.update(model_extra)
|
| 166 |
+
model_dict_new = validator(model_dict)
|
| 167 |
+
for k in list(model_dict_new.keys()):
|
| 168 |
+
if k not in fields:
|
| 169 |
+
model_extra[k] = model_dict_new.pop(k)
|
| 170 |
+
else:
|
| 171 |
+
model_dict_new = validator(model_dict)
|
| 172 |
+
return model_dict_new, model_extra, fields_set
|
| 173 |
+
|
| 174 |
+
return _wrapper2
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_discriminated_union.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Hashable, Sequence
|
| 4 |
+
from typing import TYPE_CHECKING, Any, cast
|
| 5 |
+
|
| 6 |
+
from pydantic_core import CoreSchema, core_schema
|
| 7 |
+
|
| 8 |
+
from ..errors import PydanticUserError
|
| 9 |
+
from . import _core_utils
|
| 10 |
+
from ._core_utils import (
|
| 11 |
+
CoreSchemaField,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from ..types import Discriminator
|
| 16 |
+
from ._core_metadata import CoreMetadata
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MissingDefinitionForUnionRef(Exception):
|
| 20 |
+
"""Raised when applying a discriminated union discriminator to a schema
|
| 21 |
+
requires a definition that is not yet defined
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, ref: str) -> None:
|
| 25 |
+
self.ref = ref
|
| 26 |
+
super().__init__(f'Missing definition for ref {self.ref!r}')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def set_discriminator_in_metadata(schema: CoreSchema, discriminator: Any) -> None:
|
| 30 |
+
metadata = cast('CoreMetadata', schema.setdefault('metadata', {}))
|
| 31 |
+
metadata['pydantic_internal_union_discriminator'] = discriminator
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def apply_discriminator(
|
| 35 |
+
schema: core_schema.CoreSchema,
|
| 36 |
+
discriminator: str | Discriminator,
|
| 37 |
+
definitions: dict[str, core_schema.CoreSchema] | None = None,
|
| 38 |
+
) -> core_schema.CoreSchema:
|
| 39 |
+
"""Applies the discriminator and returns a new core schema.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
schema: The input schema.
|
| 43 |
+
discriminator: The name of the field which will serve as the discriminator.
|
| 44 |
+
definitions: A mapping of schema ref to schema.
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
The new core schema.
|
| 48 |
+
|
| 49 |
+
Raises:
|
| 50 |
+
TypeError:
|
| 51 |
+
- If `discriminator` is used with invalid union variant.
|
| 52 |
+
- If `discriminator` is used with `Union` type with one variant.
|
| 53 |
+
- If `discriminator` value mapped to multiple choices.
|
| 54 |
+
MissingDefinitionForUnionRef:
|
| 55 |
+
If the definition for ref is missing.
|
| 56 |
+
PydanticUserError:
|
| 57 |
+
- If a model in union doesn't have a discriminator field.
|
| 58 |
+
- If discriminator field has a non-string alias.
|
| 59 |
+
- If discriminator fields have different aliases.
|
| 60 |
+
- If discriminator field not of type `Literal`.
|
| 61 |
+
"""
|
| 62 |
+
from ..types import Discriminator
|
| 63 |
+
|
| 64 |
+
if isinstance(discriminator, Discriminator):
|
| 65 |
+
if isinstance(discriminator.discriminator, str):
|
| 66 |
+
discriminator = discriminator.discriminator
|
| 67 |
+
else:
|
| 68 |
+
return discriminator._convert_schema(schema)
|
| 69 |
+
|
| 70 |
+
return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _ApplyInferredDiscriminator:
|
| 74 |
+
"""This class is used to convert an input schema containing a union schema into one where that union is
|
| 75 |
+
replaced with a tagged-union, with all the associated debugging and performance benefits.
|
| 76 |
+
|
| 77 |
+
This is done by:
|
| 78 |
+
* Validating that the input schema is compatible with the provided discriminator
|
| 79 |
+
* Introspecting the schema to determine which discriminator values should map to which union choices
|
| 80 |
+
* Handling various edge cases such as 'definitions', 'default', 'nullable' schemas, and more
|
| 81 |
+
|
| 82 |
+
I have chosen to implement the conversion algorithm in this class, rather than a function,
|
| 83 |
+
to make it easier to maintain state while recursively walking the provided CoreSchema.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, discriminator: str, definitions: dict[str, core_schema.CoreSchema]):
|
| 87 |
+
# `discriminator` should be the name of the field which will serve as the discriminator.
|
| 88 |
+
# It must be the python name of the field, and *not* the field's alias. Note that as of now,
|
| 89 |
+
# all members of a discriminated union _must_ use a field with the same name as the discriminator.
|
| 90 |
+
# This may change if/when we expose a way to manually specify the TaggedUnionSchema's choices.
|
| 91 |
+
self.discriminator = discriminator
|
| 92 |
+
|
| 93 |
+
# `definitions` should contain a mapping of schema ref to schema for all schemas which might
|
| 94 |
+
# be referenced by some choice
|
| 95 |
+
self.definitions = definitions
|
| 96 |
+
|
| 97 |
+
# `_discriminator_alias` will hold the value, if present, of the alias for the discriminator
|
| 98 |
+
#
|
| 99 |
+
# Note: following the v1 implementation, we currently disallow the use of different aliases
|
| 100 |
+
# for different choices. This is not a limitation of pydantic_core, but if we try to handle
|
| 101 |
+
# this, the inference logic gets complicated very quickly, and could result in confusing
|
| 102 |
+
# debugging challenges for users making subtle mistakes.
|
| 103 |
+
#
|
| 104 |
+
# Rather than trying to do the most powerful inference possible, I think we should eventually
|
| 105 |
+
# expose a way to more-manually control the way the TaggedUnionSchema is constructed through
|
| 106 |
+
# the use of a new type which would be placed as an Annotation on the Union type. This would
|
| 107 |
+
# provide the full flexibility/power of pydantic_core's TaggedUnionSchema where necessary for
|
| 108 |
+
# more complex cases, without over-complicating the inference logic for the common cases.
|
| 109 |
+
self._discriminator_alias: str | None = None
|
| 110 |
+
|
| 111 |
+
# `_should_be_nullable` indicates whether the converted union has `None` as an allowed value.
|
| 112 |
+
# If `None` is an acceptable value of the (possibly-wrapped) union, we ignore it while
|
| 113 |
+
# constructing the TaggedUnionSchema, but set the `_should_be_nullable` attribute to True.
|
| 114 |
+
# Once we have constructed the TaggedUnionSchema, if `_should_be_nullable` is True, we ensure
|
| 115 |
+
# that the final schema gets wrapped as a NullableSchema. This has the same semantics on the
|
| 116 |
+
# python side, but resolves the issue that `None` cannot correspond to any discriminator values.
|
| 117 |
+
self._should_be_nullable = False
|
| 118 |
+
|
| 119 |
+
# `_is_nullable` is used to track if the final produced schema will definitely be nullable;
|
| 120 |
+
# we set it to True if the input schema is wrapped in a nullable schema that we know will be preserved
|
| 121 |
+
# as an indication that, even if None is discovered as one of the union choices, we will not need to wrap
|
| 122 |
+
# the final value in another nullable schema.
|
| 123 |
+
#
|
| 124 |
+
# This is more complicated than just checking for the final outermost schema having type 'nullable' thanks
|
| 125 |
+
# to the possible presence of other wrapper schemas such as DefinitionsSchema, WithDefaultSchema, etc.
|
| 126 |
+
self._is_nullable = False
|
| 127 |
+
|
| 128 |
+
# `_choices_to_handle` serves as a stack of choices to add to the tagged union. Initially, choices
|
| 129 |
+
# from the union in the wrapped schema will be appended to this list, and the recursive choice-handling
|
| 130 |
+
# algorithm may add more choices to this stack as (nested) unions are encountered.
|
| 131 |
+
self._choices_to_handle: list[core_schema.CoreSchema] = []
|
| 132 |
+
|
| 133 |
+
# `_tagged_union_choices` is built during the call to `apply`, and will hold the choices to be included
|
| 134 |
+
# in the output TaggedUnionSchema that will replace the union from the input schema
|
| 135 |
+
self._tagged_union_choices: dict[Hashable, core_schema.CoreSchema] = {}
|
| 136 |
+
|
| 137 |
+
# `_used` is changed to True after applying the discriminator to prevent accidental reuse
|
| 138 |
+
self._used = False
|
| 139 |
+
|
| 140 |
+
def apply(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
|
| 141 |
+
"""Return a new CoreSchema based on `schema` that uses a tagged-union with the discriminator provided
|
| 142 |
+
to this class.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
schema: The input schema.
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
The new core schema.
|
| 149 |
+
|
| 150 |
+
Raises:
|
| 151 |
+
TypeError:
|
| 152 |
+
- If `discriminator` is used with invalid union variant.
|
| 153 |
+
- If `discriminator` is used with `Union` type with one variant.
|
| 154 |
+
- If `discriminator` value mapped to multiple choices.
|
| 155 |
+
ValueError:
|
| 156 |
+
If the definition for ref is missing.
|
| 157 |
+
PydanticUserError:
|
| 158 |
+
- If a model in union doesn't have a discriminator field.
|
| 159 |
+
- If discriminator field has a non-string alias.
|
| 160 |
+
- If discriminator fields have different aliases.
|
| 161 |
+
- If discriminator field not of type `Literal`.
|
| 162 |
+
"""
|
| 163 |
+
assert not self._used
|
| 164 |
+
schema = self._apply_to_root(schema)
|
| 165 |
+
if self._should_be_nullable and not self._is_nullable:
|
| 166 |
+
schema = core_schema.nullable_schema(schema)
|
| 167 |
+
self._used = True
|
| 168 |
+
return schema
|
| 169 |
+
|
| 170 |
+
def _apply_to_root(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
|
| 171 |
+
"""This method handles the outer-most stage of recursion over the input schema:
|
| 172 |
+
unwrapping nullable or definitions schemas, and calling the `_handle_choice`
|
| 173 |
+
method iteratively on the choices extracted (recursively) from the possibly-wrapped union.
|
| 174 |
+
"""
|
| 175 |
+
if schema['type'] == 'nullable':
|
| 176 |
+
self._is_nullable = True
|
| 177 |
+
wrapped = self._apply_to_root(schema['schema'])
|
| 178 |
+
nullable_wrapper = schema.copy()
|
| 179 |
+
nullable_wrapper['schema'] = wrapped
|
| 180 |
+
return nullable_wrapper
|
| 181 |
+
|
| 182 |
+
if schema['type'] == 'definitions':
|
| 183 |
+
wrapped = self._apply_to_root(schema['schema'])
|
| 184 |
+
definitions_wrapper = schema.copy()
|
| 185 |
+
definitions_wrapper['schema'] = wrapped
|
| 186 |
+
return definitions_wrapper
|
| 187 |
+
|
| 188 |
+
if schema['type'] != 'union':
|
| 189 |
+
# If the schema is not a union, it probably means it just had a single member and
|
| 190 |
+
# was flattened by pydantic_core.
|
| 191 |
+
# However, it still may make sense to apply the discriminator to this schema,
|
| 192 |
+
# as a way to get discriminated-union-style error messages, so we allow this here.
|
| 193 |
+
schema = core_schema.union_schema([schema])
|
| 194 |
+
|
| 195 |
+
# Reverse the choices list before extending the stack so that they get handled in the order they occur
|
| 196 |
+
choices_schemas = [v[0] if isinstance(v, tuple) else v for v in schema['choices'][::-1]]
|
| 197 |
+
self._choices_to_handle.extend(choices_schemas)
|
| 198 |
+
while self._choices_to_handle:
|
| 199 |
+
choice = self._choices_to_handle.pop()
|
| 200 |
+
self._handle_choice(choice)
|
| 201 |
+
|
| 202 |
+
if self._discriminator_alias is not None and self._discriminator_alias != self.discriminator:
|
| 203 |
+
# * We need to annotate `discriminator` as a union here to handle both branches of this conditional
|
| 204 |
+
# * We need to annotate `discriminator` as list[list[str | int]] and not list[list[str]] due to the
|
| 205 |
+
# invariance of list, and because list[list[str | int]] is the type of the discriminator argument
|
| 206 |
+
# to tagged_union_schema below
|
| 207 |
+
# * See the docstring of pydantic_core.core_schema.tagged_union_schema for more details about how to
|
| 208 |
+
# interpret the value of the discriminator argument to tagged_union_schema. (The list[list[str]] here
|
| 209 |
+
# is the appropriate way to provide a list of fallback attributes to check for a discriminator value.)
|
| 210 |
+
discriminator: str | list[list[str | int]] = [[self.discriminator], [self._discriminator_alias]]
|
| 211 |
+
else:
|
| 212 |
+
discriminator = self.discriminator
|
| 213 |
+
return core_schema.tagged_union_schema(
|
| 214 |
+
choices=self._tagged_union_choices,
|
| 215 |
+
discriminator=discriminator,
|
| 216 |
+
custom_error_type=schema.get('custom_error_type'),
|
| 217 |
+
custom_error_message=schema.get('custom_error_message'),
|
| 218 |
+
custom_error_context=schema.get('custom_error_context'),
|
| 219 |
+
strict=False,
|
| 220 |
+
from_attributes=True,
|
| 221 |
+
ref=schema.get('ref'),
|
| 222 |
+
metadata=schema.get('metadata'),
|
| 223 |
+
serialization=schema.get('serialization'),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def _handle_choice(self, choice: core_schema.CoreSchema) -> None:
|
| 227 |
+
"""This method handles the "middle" stage of recursion over the input schema.
|
| 228 |
+
Specifically, it is responsible for handling each choice of the outermost union
|
| 229 |
+
(and any "coalesced" choices obtained from inner unions).
|
| 230 |
+
|
| 231 |
+
Here, "handling" entails:
|
| 232 |
+
* Coalescing nested unions and compatible tagged-unions
|
| 233 |
+
* Tracking the presence of 'none' and 'nullable' schemas occurring as choices
|
| 234 |
+
* Validating that each allowed discriminator value maps to a unique choice
|
| 235 |
+
* Updating the _tagged_union_choices mapping that will ultimately be used to build the TaggedUnionSchema.
|
| 236 |
+
"""
|
| 237 |
+
if choice['type'] == 'definition-ref':
|
| 238 |
+
if choice['schema_ref'] not in self.definitions:
|
| 239 |
+
raise MissingDefinitionForUnionRef(choice['schema_ref'])
|
| 240 |
+
|
| 241 |
+
if choice['type'] == 'none':
|
| 242 |
+
self._should_be_nullable = True
|
| 243 |
+
elif choice['type'] == 'definitions':
|
| 244 |
+
self._handle_choice(choice['schema'])
|
| 245 |
+
elif choice['type'] == 'nullable':
|
| 246 |
+
self._should_be_nullable = True
|
| 247 |
+
self._handle_choice(choice['schema']) # unwrap the nullable schema
|
| 248 |
+
elif choice['type'] == 'union':
|
| 249 |
+
# Reverse the choices list before extending the stack so that they get handled in the order they occur
|
| 250 |
+
choices_schemas = [v[0] if isinstance(v, tuple) else v for v in choice['choices'][::-1]]
|
| 251 |
+
self._choices_to_handle.extend(choices_schemas)
|
| 252 |
+
elif choice['type'] not in {
|
| 253 |
+
'model',
|
| 254 |
+
'typed-dict',
|
| 255 |
+
'tagged-union',
|
| 256 |
+
'lax-or-strict',
|
| 257 |
+
'dataclass',
|
| 258 |
+
'dataclass-args',
|
| 259 |
+
'definition-ref',
|
| 260 |
+
} and not _core_utils.is_function_with_inner_schema(choice):
|
| 261 |
+
# We should eventually handle 'definition-ref' as well
|
| 262 |
+
err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
|
| 263 |
+
if choice['type'] == 'list':
|
| 264 |
+
err_str += (
|
| 265 |
+
' If you are making use of a list of union types, make sure the discriminator is applied to the '
|
| 266 |
+
'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
|
| 267 |
+
)
|
| 268 |
+
raise TypeError(err_str)
|
| 269 |
+
else:
|
| 270 |
+
if choice['type'] == 'tagged-union' and self._is_discriminator_shared(choice):
|
| 271 |
+
# In this case, this inner tagged-union is compatible with the outer tagged-union,
|
| 272 |
+
# and its choices can be coalesced into the outer TaggedUnionSchema.
|
| 273 |
+
subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
|
| 274 |
+
# Reverse the choices list before extending the stack so that they get handled in the order they occur
|
| 275 |
+
self._choices_to_handle.extend(subchoices[::-1])
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
inferred_discriminator_values = self._infer_discriminator_values_for_choice(choice, source_name=None)
|
| 279 |
+
self._set_unique_choice_for_values(choice, inferred_discriminator_values)
|
| 280 |
+
|
| 281 |
+
def _is_discriminator_shared(self, choice: core_schema.TaggedUnionSchema) -> bool:
|
| 282 |
+
"""This method returns a boolean indicating whether the discriminator for the `choice`
|
| 283 |
+
is the same as that being used for the outermost tagged union. This is used to
|
| 284 |
+
determine whether this TaggedUnionSchema choice should be "coalesced" into the top level,
|
| 285 |
+
or whether it should be treated as a separate (nested) choice.
|
| 286 |
+
"""
|
| 287 |
+
inner_discriminator = choice['discriminator']
|
| 288 |
+
return inner_discriminator == self.discriminator or (
|
| 289 |
+
isinstance(inner_discriminator, list)
|
| 290 |
+
and (self.discriminator in inner_discriminator or [self.discriminator] in inner_discriminator)
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
def _infer_discriminator_values_for_choice( # noqa C901
|
| 294 |
+
self, choice: core_schema.CoreSchema, source_name: str | None
|
| 295 |
+
) -> list[str | int]:
|
| 296 |
+
"""This function recurses over `choice`, extracting all discriminator values that should map to this choice.
|
| 297 |
+
|
| 298 |
+
`model_name` is accepted for the purpose of producing useful error messages.
|
| 299 |
+
"""
|
| 300 |
+
if choice['type'] == 'definitions':
|
| 301 |
+
return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
|
| 302 |
+
|
| 303 |
+
elif _core_utils.is_function_with_inner_schema(choice):
|
| 304 |
+
return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
|
| 305 |
+
|
| 306 |
+
elif choice['type'] == 'lax-or-strict':
|
| 307 |
+
return sorted(
|
| 308 |
+
set(
|
| 309 |
+
self._infer_discriminator_values_for_choice(choice['lax_schema'], source_name=None)
|
| 310 |
+
+ self._infer_discriminator_values_for_choice(choice['strict_schema'], source_name=None)
|
| 311 |
+
)
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
elif choice['type'] == 'tagged-union':
|
| 315 |
+
values: list[str | int] = []
|
| 316 |
+
# Ignore str/int "choices" since these are just references to other choices
|
| 317 |
+
subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
|
| 318 |
+
for subchoice in subchoices:
|
| 319 |
+
subchoice_values = self._infer_discriminator_values_for_choice(subchoice, source_name=None)
|
| 320 |
+
values.extend(subchoice_values)
|
| 321 |
+
return values
|
| 322 |
+
|
| 323 |
+
elif choice['type'] == 'union':
|
| 324 |
+
values = []
|
| 325 |
+
for subchoice in choice['choices']:
|
| 326 |
+
subchoice_schema = subchoice[0] if isinstance(subchoice, tuple) else subchoice
|
| 327 |
+
subchoice_values = self._infer_discriminator_values_for_choice(subchoice_schema, source_name=None)
|
| 328 |
+
values.extend(subchoice_values)
|
| 329 |
+
return values
|
| 330 |
+
|
| 331 |
+
elif choice['type'] == 'nullable':
|
| 332 |
+
self._should_be_nullable = True
|
| 333 |
+
return self._infer_discriminator_values_for_choice(choice['schema'], source_name=None)
|
| 334 |
+
|
| 335 |
+
elif choice['type'] == 'model':
|
| 336 |
+
return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
|
| 337 |
+
|
| 338 |
+
elif choice['type'] == 'dataclass':
|
| 339 |
+
return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
|
| 340 |
+
|
| 341 |
+
elif choice['type'] == 'model-fields':
|
| 342 |
+
return self._infer_discriminator_values_for_model_choice(choice, source_name=source_name)
|
| 343 |
+
|
| 344 |
+
elif choice['type'] == 'dataclass-args':
|
| 345 |
+
return self._infer_discriminator_values_for_dataclass_choice(choice, source_name=source_name)
|
| 346 |
+
|
| 347 |
+
elif choice['type'] == 'typed-dict':
|
| 348 |
+
return self._infer_discriminator_values_for_typed_dict_choice(choice, source_name=source_name)
|
| 349 |
+
|
| 350 |
+
elif choice['type'] == 'definition-ref':
|
| 351 |
+
schema_ref = choice['schema_ref']
|
| 352 |
+
if schema_ref not in self.definitions:
|
| 353 |
+
raise MissingDefinitionForUnionRef(schema_ref)
|
| 354 |
+
return self._infer_discriminator_values_for_choice(self.definitions[schema_ref], source_name=source_name)
|
| 355 |
+
else:
|
| 356 |
+
err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
|
| 357 |
+
if choice['type'] == 'list':
|
| 358 |
+
err_str += (
|
| 359 |
+
' If you are making use of a list of union types, make sure the discriminator is applied to the '
|
| 360 |
+
'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
|
| 361 |
+
)
|
| 362 |
+
raise TypeError(err_str)
|
| 363 |
+
|
| 364 |
+
def _infer_discriminator_values_for_typed_dict_choice(
|
| 365 |
+
self, choice: core_schema.TypedDictSchema, source_name: str | None = None
|
| 366 |
+
) -> list[str | int]:
|
| 367 |
+
"""This method just extracts the _infer_discriminator_values_for_choice logic specific to TypedDictSchema
|
| 368 |
+
for the sake of readability.
|
| 369 |
+
"""
|
| 370 |
+
source = 'TypedDict' if source_name is None else f'TypedDict {source_name!r}'
|
| 371 |
+
field = choice['fields'].get(self.discriminator)
|
| 372 |
+
if field is None:
|
| 373 |
+
raise PydanticUserError(
|
| 374 |
+
f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
|
| 375 |
+
)
|
| 376 |
+
return self._infer_discriminator_values_for_field(field, source)
|
| 377 |
+
|
| 378 |
+
def _infer_discriminator_values_for_model_choice(
|
| 379 |
+
self, choice: core_schema.ModelFieldsSchema, source_name: str | None = None
|
| 380 |
+
) -> list[str | int]:
|
| 381 |
+
source = 'ModelFields' if source_name is None else f'Model {source_name!r}'
|
| 382 |
+
field = choice['fields'].get(self.discriminator)
|
| 383 |
+
if field is None:
|
| 384 |
+
raise PydanticUserError(
|
| 385 |
+
f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
|
| 386 |
+
)
|
| 387 |
+
return self._infer_discriminator_values_for_field(field, source)
|
| 388 |
+
|
| 389 |
+
def _infer_discriminator_values_for_dataclass_choice(
|
| 390 |
+
self, choice: core_schema.DataclassArgsSchema, source_name: str | None = None
|
| 391 |
+
) -> list[str | int]:
|
| 392 |
+
source = 'DataclassArgs' if source_name is None else f'Dataclass {source_name!r}'
|
| 393 |
+
for field in choice['fields']:
|
| 394 |
+
if field['name'] == self.discriminator:
|
| 395 |
+
break
|
| 396 |
+
else:
|
| 397 |
+
raise PydanticUserError(
|
| 398 |
+
f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
|
| 399 |
+
)
|
| 400 |
+
return self._infer_discriminator_values_for_field(field, source)
|
| 401 |
+
|
| 402 |
+
def _infer_discriminator_values_for_field(self, field: CoreSchemaField, source: str) -> list[str | int]:
|
| 403 |
+
if field['type'] == 'computed-field':
|
| 404 |
+
# This should never occur as a discriminator, as it is only relevant to serialization
|
| 405 |
+
return []
|
| 406 |
+
alias = field.get('validation_alias', self.discriminator)
|
| 407 |
+
if not isinstance(alias, str):
|
| 408 |
+
raise PydanticUserError(
|
| 409 |
+
f'Alias {alias!r} is not supported in a discriminated union', code='discriminator-alias-type'
|
| 410 |
+
)
|
| 411 |
+
if self._discriminator_alias is None:
|
| 412 |
+
self._discriminator_alias = alias
|
| 413 |
+
elif self._discriminator_alias != alias:
|
| 414 |
+
raise PydanticUserError(
|
| 415 |
+
f'Aliases for discriminator {self.discriminator!r} must be the same '
|
| 416 |
+
f'(got {alias}, {self._discriminator_alias})',
|
| 417 |
+
code='discriminator-alias',
|
| 418 |
+
)
|
| 419 |
+
return self._infer_discriminator_values_for_inner_schema(field['schema'], source)
|
| 420 |
+
|
| 421 |
+
def _infer_discriminator_values_for_inner_schema(
|
| 422 |
+
self, schema: core_schema.CoreSchema, source: str
|
| 423 |
+
) -> list[str | int]:
|
| 424 |
+
"""When inferring discriminator values for a field, we typically extract the expected values from a literal
|
| 425 |
+
schema. This function does that, but also handles nested unions and defaults.
|
| 426 |
+
"""
|
| 427 |
+
if schema['type'] == 'literal':
|
| 428 |
+
return schema['expected']
|
| 429 |
+
|
| 430 |
+
elif schema['type'] == 'union':
|
| 431 |
+
# Generally when multiple values are allowed they should be placed in a single `Literal`, but
|
| 432 |
+
# we add this case to handle the situation where a field is annotated as a `Union` of `Literal`s.
|
| 433 |
+
# For example, this lets us handle `Union[Literal['key'], Union[Literal['Key'], Literal['KEY']]]`
|
| 434 |
+
values: list[Any] = []
|
| 435 |
+
for choice in schema['choices']:
|
| 436 |
+
choice_schema = choice[0] if isinstance(choice, tuple) else choice
|
| 437 |
+
choice_values = self._infer_discriminator_values_for_inner_schema(choice_schema, source)
|
| 438 |
+
values.extend(choice_values)
|
| 439 |
+
return values
|
| 440 |
+
|
| 441 |
+
elif schema['type'] == 'default':
|
| 442 |
+
# This will happen if the field has a default value; we ignore it while extracting the discriminator values
|
| 443 |
+
return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
|
| 444 |
+
|
| 445 |
+
elif schema['type'] == 'function-after':
|
| 446 |
+
# After validators don't affect the discriminator values
|
| 447 |
+
return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
|
| 448 |
+
|
| 449 |
+
elif schema['type'] in {'function-before', 'function-wrap', 'function-plain'}:
|
| 450 |
+
validator_type = repr(schema['type'].split('-')[1])
|
| 451 |
+
raise PydanticUserError(
|
| 452 |
+
f'Cannot use a mode={validator_type} validator in the'
|
| 453 |
+
f' discriminator field {self.discriminator!r} of {source}',
|
| 454 |
+
code='discriminator-validator',
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
else:
|
| 458 |
+
raise PydanticUserError(
|
| 459 |
+
f'{source} needs field {self.discriminator!r} to be of type `Literal`',
|
| 460 |
+
code='discriminator-needs-literal',
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
def _set_unique_choice_for_values(self, choice: core_schema.CoreSchema, values: Sequence[str | int]) -> None:
|
| 464 |
+
"""This method updates `self.tagged_union_choices` so that all provided (discriminator) `values` map to the
|
| 465 |
+
provided `choice`, validating that none of these values already map to another (different) choice.
|
| 466 |
+
"""
|
| 467 |
+
for discriminator_value in values:
|
| 468 |
+
if discriminator_value in self._tagged_union_choices:
|
| 469 |
+
# It is okay if `value` is already in tagged_union_choices as long as it maps to the same value.
|
| 470 |
+
# Because tagged_union_choices may map values to other values, we need to walk the choices dict
|
| 471 |
+
# until we get to a "real" choice, and confirm that is equal to the one assigned.
|
| 472 |
+
existing_choice = self._tagged_union_choices[discriminator_value]
|
| 473 |
+
if existing_choice != choice:
|
| 474 |
+
raise TypeError(
|
| 475 |
+
f'Value {discriminator_value!r} for discriminator '
|
| 476 |
+
f'{self.discriminator!r} mapped to multiple choices'
|
| 477 |
+
)
|
| 478 |
+
else:
|
| 479 |
+
self._tagged_union_choices[discriminator_value] = choice
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_docs_extraction.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities related to attribute docstring extraction."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import ast
|
| 6 |
+
import inspect
|
| 7 |
+
import sys
|
| 8 |
+
import textwrap
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DocstringVisitor(ast.NodeVisitor):
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
super().__init__()
|
| 15 |
+
|
| 16 |
+
self.target: str | None = None
|
| 17 |
+
self.attrs: dict[str, str] = {}
|
| 18 |
+
self.previous_node_type: type[ast.AST] | None = None
|
| 19 |
+
|
| 20 |
+
def visit(self, node: ast.AST) -> Any:
|
| 21 |
+
node_result = super().visit(node)
|
| 22 |
+
self.previous_node_type = type(node)
|
| 23 |
+
return node_result
|
| 24 |
+
|
| 25 |
+
def visit_AnnAssign(self, node: ast.AnnAssign) -> Any:
|
| 26 |
+
if isinstance(node.target, ast.Name):
|
| 27 |
+
self.target = node.target.id
|
| 28 |
+
|
| 29 |
+
def visit_Expr(self, node: ast.Expr) -> Any:
|
| 30 |
+
if (
|
| 31 |
+
isinstance(node.value, ast.Constant)
|
| 32 |
+
and isinstance(node.value.value, str)
|
| 33 |
+
and self.previous_node_type is ast.AnnAssign
|
| 34 |
+
):
|
| 35 |
+
docstring = inspect.cleandoc(node.value.value)
|
| 36 |
+
if self.target:
|
| 37 |
+
self.attrs[self.target] = docstring
|
| 38 |
+
self.target = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _dedent_source_lines(source: list[str]) -> str:
|
| 42 |
+
# Required for nested class definitions, e.g. in a function block
|
| 43 |
+
dedent_source = textwrap.dedent(''.join(source))
|
| 44 |
+
if dedent_source.startswith((' ', '\t')):
|
| 45 |
+
# We are in the case where there's a dedented (usually multiline) string
|
| 46 |
+
# at a lower indentation level than the class itself. We wrap our class
|
| 47 |
+
# in a function as a workaround.
|
| 48 |
+
dedent_source = f'def dedent_workaround():\n{dedent_source}'
|
| 49 |
+
return dedent_source
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _extract_source_from_frame(cls: type[Any]) -> list[str] | None:
|
| 53 |
+
frame = inspect.currentframe()
|
| 54 |
+
|
| 55 |
+
while frame:
|
| 56 |
+
if inspect.getmodule(frame) is inspect.getmodule(cls):
|
| 57 |
+
lnum = frame.f_lineno
|
| 58 |
+
try:
|
| 59 |
+
lines, _ = inspect.findsource(frame)
|
| 60 |
+
except OSError: # pragma: no cover
|
| 61 |
+
# Source can't be retrieved (maybe because running in an interactive terminal),
|
| 62 |
+
# we don't want to error here.
|
| 63 |
+
pass
|
| 64 |
+
else:
|
| 65 |
+
block_lines = inspect.getblock(lines[lnum - 1 :])
|
| 66 |
+
dedent_source = _dedent_source_lines(block_lines)
|
| 67 |
+
try:
|
| 68 |
+
block_tree = ast.parse(dedent_source)
|
| 69 |
+
except SyntaxError:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
stmt = block_tree.body[0]
|
| 73 |
+
if isinstance(stmt, ast.FunctionDef) and stmt.name == 'dedent_workaround':
|
| 74 |
+
# `_dedent_source_lines` wrapped the class around the workaround function
|
| 75 |
+
stmt = stmt.body[0]
|
| 76 |
+
if isinstance(stmt, ast.ClassDef) and stmt.name == cls.__name__:
|
| 77 |
+
return block_lines
|
| 78 |
+
|
| 79 |
+
frame = frame.f_back
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def extract_docstrings_from_cls(cls: type[Any], use_inspect: bool = False) -> dict[str, str]:
|
| 83 |
+
"""Map model attributes and their corresponding docstring.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
cls: The class of the Pydantic model to inspect.
|
| 87 |
+
use_inspect: Whether to skip usage of frames to find the object and use
|
| 88 |
+
the `inspect` module instead.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
A mapping containing attribute names and their corresponding docstring.
|
| 92 |
+
"""
|
| 93 |
+
if use_inspect or sys.version_info >= (3, 13):
|
| 94 |
+
# On Python < 3.13, `inspect.getsourcelines()` might not work as expected
|
| 95 |
+
# if two classes have the same name in the same source file.
|
| 96 |
+
# On Python 3.13+, it will use the new `__firstlineno__` class attribute,
|
| 97 |
+
# making it way more robust.
|
| 98 |
+
try:
|
| 99 |
+
source, _ = inspect.getsourcelines(cls)
|
| 100 |
+
except OSError: # pragma: no cover
|
| 101 |
+
return {}
|
| 102 |
+
else:
|
| 103 |
+
# TODO remove this implementation when we drop support for Python 3.12:
|
| 104 |
+
source = _extract_source_from_frame(cls)
|
| 105 |
+
|
| 106 |
+
if not source:
|
| 107 |
+
return {}
|
| 108 |
+
|
| 109 |
+
dedent_source = _dedent_source_lines(source)
|
| 110 |
+
|
| 111 |
+
visitor = DocstringVisitor()
|
| 112 |
+
visitor.visit(ast.parse(dedent_source))
|
| 113 |
+
return visitor.attrs
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_fields.py
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
import warnings
|
| 7 |
+
from collections.abc import Mapping
|
| 8 |
+
from functools import cache
|
| 9 |
+
from inspect import Parameter, ismethoddescriptor, signature
|
| 10 |
+
from re import Pattern
|
| 11 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar
|
| 12 |
+
|
| 13 |
+
from pydantic_core import PydanticUndefined
|
| 14 |
+
from typing_extensions import TypeIs
|
| 15 |
+
from typing_inspection.introspection import AnnotationSource
|
| 16 |
+
|
| 17 |
+
from pydantic import PydanticDeprecatedSince211
|
| 18 |
+
from pydantic.errors import PydanticUserError
|
| 19 |
+
|
| 20 |
+
from ..aliases import AliasGenerator
|
| 21 |
+
from . import _generics, _typing_extra
|
| 22 |
+
from ._config import ConfigWrapper
|
| 23 |
+
from ._docs_extraction import extract_docstrings_from_cls
|
| 24 |
+
from ._import_utils import import_cached_base_model, import_cached_field_info
|
| 25 |
+
from ._namespace_utils import NsResolver
|
| 26 |
+
from ._repr import Representation
|
| 27 |
+
from ._utils import can_be_positional, get_first_not_none
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from annotated_types import BaseMetadata
|
| 31 |
+
|
| 32 |
+
from ..fields import FieldInfo
|
| 33 |
+
from ..main import BaseModel
|
| 34 |
+
from ._dataclasses import PydanticDataclass, StandardDataclass
|
| 35 |
+
from ._decorators import DecoratorInfos
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PydanticMetadata(Representation):
|
| 39 |
+
"""Base class for annotation markers like `Strict`."""
|
| 40 |
+
|
| 41 |
+
__slots__ = ()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def pydantic_general_metadata(**metadata: Any) -> BaseMetadata:
|
| 45 |
+
"""Create a new `_PydanticGeneralMetadata` class with the given metadata.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
**metadata: The metadata to add.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
The new `_PydanticGeneralMetadata` class.
|
| 52 |
+
"""
|
| 53 |
+
return _general_metadata_cls()(metadata) # type: ignore
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@cache
|
| 57 |
+
def _general_metadata_cls() -> type[BaseMetadata]:
|
| 58 |
+
"""Do it this way to avoid importing `annotated_types` at import time."""
|
| 59 |
+
from annotated_types import BaseMetadata
|
| 60 |
+
|
| 61 |
+
class _PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):
|
| 62 |
+
"""Pydantic general metadata like `max_digits`."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, metadata: Any):
|
| 65 |
+
self.__dict__ = metadata
|
| 66 |
+
|
| 67 |
+
return _PydanticGeneralMetadata # type: ignore
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _check_protected_namespaces(
|
| 71 |
+
protected_namespaces: tuple[str | Pattern[str], ...],
|
| 72 |
+
ann_name: str,
|
| 73 |
+
bases: tuple[type[Any], ...],
|
| 74 |
+
cls_name: str,
|
| 75 |
+
) -> None:
|
| 76 |
+
BaseModel = import_cached_base_model()
|
| 77 |
+
|
| 78 |
+
for protected_namespace in protected_namespaces:
|
| 79 |
+
ns_violation = False
|
| 80 |
+
if isinstance(protected_namespace, Pattern):
|
| 81 |
+
ns_violation = protected_namespace.match(ann_name) is not None
|
| 82 |
+
elif isinstance(protected_namespace, str):
|
| 83 |
+
ns_violation = ann_name.startswith(protected_namespace)
|
| 84 |
+
|
| 85 |
+
if ns_violation:
|
| 86 |
+
for b in bases:
|
| 87 |
+
if hasattr(b, ann_name):
|
| 88 |
+
if not (issubclass(b, BaseModel) and ann_name in getattr(b, '__pydantic_fields__', {})):
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f'Field {ann_name!r} conflicts with member {getattr(b, ann_name)}'
|
| 91 |
+
f' of protected namespace {protected_namespace!r}.'
|
| 92 |
+
)
|
| 93 |
+
else:
|
| 94 |
+
valid_namespaces: list[str] = []
|
| 95 |
+
for pn in protected_namespaces:
|
| 96 |
+
if isinstance(pn, Pattern):
|
| 97 |
+
if not pn.match(ann_name):
|
| 98 |
+
valid_namespaces.append(f're.compile({pn.pattern!r})')
|
| 99 |
+
else:
|
| 100 |
+
if not ann_name.startswith(pn):
|
| 101 |
+
valid_namespaces.append(f"'{pn}'")
|
| 102 |
+
|
| 103 |
+
valid_namespaces_str = f'({", ".join(valid_namespaces)}{",)" if len(valid_namespaces) == 1 else ")"}'
|
| 104 |
+
|
| 105 |
+
warnings.warn(
|
| 106 |
+
f'Field {ann_name!r} in {cls_name!r} conflicts with protected namespace {protected_namespace!r}.\n\n'
|
| 107 |
+
f"You may be able to solve this by setting the 'protected_namespaces' configuration to {valid_namespaces_str}.",
|
| 108 |
+
UserWarning,
|
| 109 |
+
stacklevel=5,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], use_inspect: bool = False) -> None:
|
| 114 |
+
fields_docs = extract_docstrings_from_cls(cls, use_inspect=use_inspect)
|
| 115 |
+
for ann_name, field_info in fields.items():
|
| 116 |
+
if field_info.description is None and ann_name in fields_docs:
|
| 117 |
+
field_info.description = fields_docs[ann_name]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _apply_field_title_generator_to_field_info(
|
| 121 |
+
title_generator: Callable[[str, FieldInfo], str],
|
| 122 |
+
field_name: str,
|
| 123 |
+
field_info: FieldInfo,
|
| 124 |
+
):
|
| 125 |
+
if field_info.title is None:
|
| 126 |
+
title = title_generator(field_name, field_info)
|
| 127 |
+
if not isinstance(title, str):
|
| 128 |
+
raise TypeError(f'field_title_generator {title_generator} must return str, not {title.__class__}')
|
| 129 |
+
|
| 130 |
+
field_info.title = title
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _apply_alias_generator_to_field_info(
|
| 134 |
+
alias_generator: Callable[[str], str] | AliasGenerator, field_name: str, field_info: FieldInfo
|
| 135 |
+
):
|
| 136 |
+
"""Apply an alias generator to aliases on a `FieldInfo` instance if appropriate.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
|
| 140 |
+
field_name: The name of the field from which to generate the alias.
|
| 141 |
+
field_info: The `FieldInfo` instance to which the alias generator is (maybe) applied.
|
| 142 |
+
"""
|
| 143 |
+
# Apply an alias_generator if
|
| 144 |
+
# 1. An alias is not specified
|
| 145 |
+
# 2. An alias is specified, but the priority is <= 1
|
| 146 |
+
if (
|
| 147 |
+
field_info.alias_priority is None
|
| 148 |
+
or field_info.alias_priority <= 1
|
| 149 |
+
or field_info.alias is None
|
| 150 |
+
or field_info.validation_alias is None
|
| 151 |
+
or field_info.serialization_alias is None
|
| 152 |
+
):
|
| 153 |
+
alias, validation_alias, serialization_alias = None, None, None
|
| 154 |
+
|
| 155 |
+
if isinstance(alias_generator, AliasGenerator):
|
| 156 |
+
alias, validation_alias, serialization_alias = alias_generator.generate_aliases(field_name)
|
| 157 |
+
elif callable(alias_generator):
|
| 158 |
+
alias = alias_generator(field_name)
|
| 159 |
+
if not isinstance(alias, str):
|
| 160 |
+
raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}')
|
| 161 |
+
|
| 162 |
+
# if priority is not set, we set to 1
|
| 163 |
+
# which supports the case where the alias_generator from a child class is used
|
| 164 |
+
# to generate an alias for a field in a parent class
|
| 165 |
+
if field_info.alias_priority is None or field_info.alias_priority <= 1:
|
| 166 |
+
field_info.alias_priority = 1
|
| 167 |
+
|
| 168 |
+
# if the priority is 1, then we set the aliases to the generated alias
|
| 169 |
+
if field_info.alias_priority == 1:
|
| 170 |
+
field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
|
| 171 |
+
field_info.validation_alias = get_first_not_none(validation_alias, alias)
|
| 172 |
+
field_info.alias = alias
|
| 173 |
+
|
| 174 |
+
# if any of the aliases are not set, then we set them to the corresponding generated alias
|
| 175 |
+
if field_info.alias is None:
|
| 176 |
+
field_info.alias = alias
|
| 177 |
+
if field_info.serialization_alias is None:
|
| 178 |
+
field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
|
| 179 |
+
if field_info.validation_alias is None:
|
| 180 |
+
field_info.validation_alias = get_first_not_none(validation_alias, alias)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def update_field_from_config(config_wrapper: ConfigWrapper, field_name: str, field_info: FieldInfo) -> None:
|
| 184 |
+
"""Update the `FieldInfo` instance from the configuration set on the model it belongs to.
|
| 185 |
+
|
| 186 |
+
This will apply the title and alias generators from the configuration.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
config_wrapper: The configuration from the model.
|
| 190 |
+
field_name: The field name the `FieldInfo` instance is attached to.
|
| 191 |
+
field_info: The `FieldInfo` instance to update.
|
| 192 |
+
"""
|
| 193 |
+
field_title_generator = field_info.field_title_generator or config_wrapper.field_title_generator
|
| 194 |
+
if field_title_generator is not None:
|
| 195 |
+
_apply_field_title_generator_to_field_info(field_title_generator, field_name, field_info)
|
| 196 |
+
if config_wrapper.alias_generator is not None:
|
| 197 |
+
_apply_alias_generator_to_field_info(config_wrapper.alias_generator, field_name, field_info)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
_deprecated_method_names = {'dict', 'json', 'copy', '_iter', '_copy_and_set_values', '_calculate_keys'}
|
| 201 |
+
|
| 202 |
+
_deprecated_classmethod_names = {
|
| 203 |
+
'parse_obj',
|
| 204 |
+
'parse_raw',
|
| 205 |
+
'parse_file',
|
| 206 |
+
'from_orm',
|
| 207 |
+
'construct',
|
| 208 |
+
'schema',
|
| 209 |
+
'schema_json',
|
| 210 |
+
'validate',
|
| 211 |
+
'update_forward_refs',
|
| 212 |
+
'_get_value',
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def collect_model_fields( # noqa: C901
|
| 217 |
+
cls: type[BaseModel],
|
| 218 |
+
config_wrapper: ConfigWrapper,
|
| 219 |
+
ns_resolver: NsResolver | None,
|
| 220 |
+
*,
|
| 221 |
+
typevars_map: Mapping[TypeVar, Any] | None = None,
|
| 222 |
+
) -> tuple[dict[str, FieldInfo], set[str]]:
|
| 223 |
+
"""Collect the fields and class variables names of a nascent Pydantic model.
|
| 224 |
+
|
| 225 |
+
The fields collection process is *lenient*, meaning it won't error if string annotations
|
| 226 |
+
fail to evaluate. If this happens, the original annotation (and assigned value, if any)
|
| 227 |
+
is stored on the created `FieldInfo` instance.
|
| 228 |
+
|
| 229 |
+
The `rebuild_model_fields()` should be called at a later point (e.g. when rebuilding the model),
|
| 230 |
+
and will make use of these stored attributes.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
cls: BaseModel or dataclass.
|
| 234 |
+
config_wrapper: The config wrapper instance.
|
| 235 |
+
ns_resolver: Namespace resolver to use when getting model annotations.
|
| 236 |
+
typevars_map: A dictionary mapping type variables to their concrete types.
|
| 237 |
+
|
| 238 |
+
Returns:
|
| 239 |
+
A two-tuple containing model fields and class variables names.
|
| 240 |
+
|
| 241 |
+
Raises:
|
| 242 |
+
NameError:
|
| 243 |
+
- If there is a conflict between a field name and protected namespaces.
|
| 244 |
+
- If there is a field other than `root` in `RootModel`.
|
| 245 |
+
- If a field shadows an attribute in the parent model.
|
| 246 |
+
"""
|
| 247 |
+
FieldInfo_ = import_cached_field_info()
|
| 248 |
+
BaseModel_ = import_cached_base_model()
|
| 249 |
+
|
| 250 |
+
bases = cls.__bases__
|
| 251 |
+
parent_fields_lookup: dict[str, FieldInfo] = {}
|
| 252 |
+
for base in reversed(bases):
|
| 253 |
+
if model_fields := getattr(base, '__pydantic_fields__', None):
|
| 254 |
+
parent_fields_lookup.update(model_fields)
|
| 255 |
+
|
| 256 |
+
type_hints = _typing_extra.get_model_type_hints(cls, ns_resolver=ns_resolver)
|
| 257 |
+
|
| 258 |
+
# https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
|
| 259 |
+
# annotations is only used for finding fields in parent classes
|
| 260 |
+
annotations = _typing_extra.safe_get_annotations(cls)
|
| 261 |
+
|
| 262 |
+
fields: dict[str, FieldInfo] = {}
|
| 263 |
+
|
| 264 |
+
class_vars: set[str] = set()
|
| 265 |
+
for ann_name, (ann_type, evaluated) in type_hints.items():
|
| 266 |
+
if ann_name == 'model_config':
|
| 267 |
+
# We never want to treat `model_config` as a field
|
| 268 |
+
# Note: we may need to change this logic if/when we introduce a `BareModel` class with no
|
| 269 |
+
# protected namespaces (where `model_config` might be allowed as a field name)
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
_check_protected_namespaces(
|
| 273 |
+
protected_namespaces=config_wrapper.protected_namespaces,
|
| 274 |
+
ann_name=ann_name,
|
| 275 |
+
bases=bases,
|
| 276 |
+
cls_name=cls.__name__,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
if _typing_extra.is_classvar_annotation(ann_type):
|
| 280 |
+
class_vars.add(ann_name)
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
assigned_value = getattr(cls, ann_name, PydanticUndefined)
|
| 284 |
+
if assigned_value is not PydanticUndefined and (
|
| 285 |
+
# One of the deprecated instance methods was used as a field name (e.g. `dict()`):
|
| 286 |
+
any(getattr(BaseModel_, depr_name, None) is assigned_value for depr_name in _deprecated_method_names)
|
| 287 |
+
# One of the deprecated class methods was used as a field name (e.g. `schema()`):
|
| 288 |
+
or (
|
| 289 |
+
hasattr(assigned_value, '__func__')
|
| 290 |
+
and any(
|
| 291 |
+
getattr(getattr(BaseModel_, depr_name, None), '__func__', None) is assigned_value.__func__ # pyright: ignore[reportAttributeAccessIssue]
|
| 292 |
+
for depr_name in _deprecated_classmethod_names
|
| 293 |
+
)
|
| 294 |
+
)
|
| 295 |
+
):
|
| 296 |
+
# Then `assigned_value` would be the method, even though no default was specified:
|
| 297 |
+
assigned_value = PydanticUndefined
|
| 298 |
+
|
| 299 |
+
if not is_valid_field_name(ann_name):
|
| 300 |
+
continue
|
| 301 |
+
if cls.__pydantic_root_model__ and ann_name != 'root':
|
| 302 |
+
raise NameError(
|
| 303 |
+
f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`"
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
# when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get
|
| 307 |
+
# "... shadows an attribute" warnings
|
| 308 |
+
generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')
|
| 309 |
+
for base in bases:
|
| 310 |
+
dataclass_fields = {
|
| 311 |
+
field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())
|
| 312 |
+
}
|
| 313 |
+
if hasattr(base, ann_name):
|
| 314 |
+
if base is generic_origin:
|
| 315 |
+
# Don't warn when "shadowing" of attributes in parametrized generics
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
if ann_name in dataclass_fields:
|
| 319 |
+
# Don't warn when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set
|
| 320 |
+
# on the class instance.
|
| 321 |
+
continue
|
| 322 |
+
|
| 323 |
+
if ann_name not in annotations:
|
| 324 |
+
# Don't warn when a field exists in a parent class but has not been defined in the current class
|
| 325 |
+
continue
|
| 326 |
+
|
| 327 |
+
warnings.warn(
|
| 328 |
+
f'Field name "{ann_name}" in "{cls.__qualname__}" shadows an attribute in parent '
|
| 329 |
+
f'"{base.__qualname__}"',
|
| 330 |
+
UserWarning,
|
| 331 |
+
stacklevel=4,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
if assigned_value is PydanticUndefined: # no assignment, just a plain annotation
|
| 335 |
+
if ann_name in annotations or ann_name not in parent_fields_lookup:
|
| 336 |
+
# field is either:
|
| 337 |
+
# - present in the current model's annotations (and *not* from parent classes)
|
| 338 |
+
# - not found on any base classes; this seems to be caused by fields bot getting
|
| 339 |
+
# generated due to models not being fully defined while initializing recursive models.
|
| 340 |
+
# Nothing stops us from just creating a `FieldInfo` for this type hint, so we do this.
|
| 341 |
+
field_info = FieldInfo_.from_annotation(ann_type, _source=AnnotationSource.CLASS)
|
| 342 |
+
if not evaluated:
|
| 343 |
+
field_info._complete = False
|
| 344 |
+
# Store the original annotation that should be used to rebuild
|
| 345 |
+
# the field info later:
|
| 346 |
+
field_info._original_annotation = ann_type
|
| 347 |
+
else:
|
| 348 |
+
# The field was present on one of the (possibly multiple) base classes
|
| 349 |
+
# copy the field to make sure typevar substitutions don't cause issues with the base classes
|
| 350 |
+
field_info = parent_fields_lookup[ann_name]._copy()
|
| 351 |
+
|
| 352 |
+
else: # An assigned value is present (either the default value, or a `Field()` function)
|
| 353 |
+
if isinstance(assigned_value, FieldInfo_) and ismethoddescriptor(assigned_value.default):
|
| 354 |
+
# `assigned_value` was fetched using `getattr`, which triggers a call to `__get__`
|
| 355 |
+
# for descriptors, so we do the same if the `= field(default=...)` form is used.
|
| 356 |
+
# Note that we only do this for method descriptors for now, we might want to
|
| 357 |
+
# extend this to any descriptor in the future (by simply checking for
|
| 358 |
+
# `hasattr(assigned_value.default, '__get__')`).
|
| 359 |
+
default = assigned_value.default.__get__(None, cls)
|
| 360 |
+
assigned_value.default = default
|
| 361 |
+
assigned_value._attributes_set['default'] = default
|
| 362 |
+
|
| 363 |
+
field_info = FieldInfo_.from_annotated_attribute(ann_type, assigned_value, _source=AnnotationSource.CLASS)
|
| 364 |
+
# Store the original annotation and assignment value that should be used to rebuild the field info later.
|
| 365 |
+
# Note that the assignment is always stored as the annotation might contain a type var that is later
|
| 366 |
+
# parameterized with an unknown forward reference (and we'll need it to rebuild the field info):
|
| 367 |
+
field_info._original_assignment = assigned_value
|
| 368 |
+
if not evaluated:
|
| 369 |
+
field_info._complete = False
|
| 370 |
+
field_info._original_annotation = ann_type
|
| 371 |
+
elif 'final' in field_info._qualifiers and not field_info.is_required():
|
| 372 |
+
warnings.warn(
|
| 373 |
+
f'Annotation {ann_name!r} is marked as final and has a default value. Pydantic treats {ann_name!r} as a '
|
| 374 |
+
'class variable, but it will be considered as a normal field in V3 to be aligned with dataclasses. If you '
|
| 375 |
+
f'still want {ann_name!r} to be considered as a class variable, annotate it as: `ClassVar[<type>] = <default>.`',
|
| 376 |
+
category=PydanticDeprecatedSince211,
|
| 377 |
+
# Incorrect when `create_model` is used, but the chance that final with a default is used is low in that case:
|
| 378 |
+
stacklevel=4,
|
| 379 |
+
)
|
| 380 |
+
class_vars.add(ann_name)
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
# attributes which are fields are removed from the class namespace:
|
| 384 |
+
# 1. To match the behaviour of annotation-only fields
|
| 385 |
+
# 2. To avoid false positives in the NameError check above
|
| 386 |
+
try:
|
| 387 |
+
delattr(cls, ann_name)
|
| 388 |
+
except AttributeError:
|
| 389 |
+
pass # indicates the attribute was on a parent class
|
| 390 |
+
|
| 391 |
+
# Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
|
| 392 |
+
# to make sure the decorators have already been built for this exact class
|
| 393 |
+
decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
|
| 394 |
+
if ann_name in decorators.computed_fields:
|
| 395 |
+
raise TypeError(
|
| 396 |
+
f'Field {ann_name!r} of class {cls.__name__!r} overrides symbol of same name in a parent class. '
|
| 397 |
+
'This override with a computed_field is incompatible.'
|
| 398 |
+
)
|
| 399 |
+
fields[ann_name] = field_info
|
| 400 |
+
|
| 401 |
+
if field_info._complete:
|
| 402 |
+
# If not complete, this will be called in `rebuild_model_fields()`:
|
| 403 |
+
update_field_from_config(config_wrapper, ann_name, field_info)
|
| 404 |
+
|
| 405 |
+
if typevars_map:
|
| 406 |
+
for field in fields.values():
|
| 407 |
+
if field._complete:
|
| 408 |
+
field.apply_typevars_map(typevars_map)
|
| 409 |
+
|
| 410 |
+
if config_wrapper.use_attribute_docstrings:
|
| 411 |
+
_update_fields_from_docstrings(cls, fields)
|
| 412 |
+
return fields, class_vars
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def rebuild_model_fields(
|
| 416 |
+
cls: type[BaseModel],
|
| 417 |
+
*,
|
| 418 |
+
config_wrapper: ConfigWrapper,
|
| 419 |
+
ns_resolver: NsResolver,
|
| 420 |
+
typevars_map: Mapping[TypeVar, Any],
|
| 421 |
+
) -> dict[str, FieldInfo]:
|
| 422 |
+
"""Rebuild the (already present) model fields by trying to reevaluate annotations.
|
| 423 |
+
|
| 424 |
+
This function should be called whenever a model with incomplete fields is encountered.
|
| 425 |
+
|
| 426 |
+
Raises:
|
| 427 |
+
NameError: If one of the annotations failed to evaluate.
|
| 428 |
+
|
| 429 |
+
Note:
|
| 430 |
+
This function *doesn't* mutate the model fields in place, as it can be called during
|
| 431 |
+
schema generation, where you don't want to mutate other model's fields.
|
| 432 |
+
"""
|
| 433 |
+
FieldInfo_ = import_cached_field_info()
|
| 434 |
+
|
| 435 |
+
rebuilt_fields: dict[str, FieldInfo] = {}
|
| 436 |
+
with ns_resolver.push(cls):
|
| 437 |
+
for f_name, field_info in cls.__pydantic_fields__.items():
|
| 438 |
+
if field_info._complete:
|
| 439 |
+
rebuilt_fields[f_name] = field_info
|
| 440 |
+
else:
|
| 441 |
+
existing_desc = field_info.description
|
| 442 |
+
ann = _typing_extra.eval_type(
|
| 443 |
+
field_info._original_annotation,
|
| 444 |
+
*ns_resolver.types_namespace,
|
| 445 |
+
)
|
| 446 |
+
ann = _generics.replace_types(ann, typevars_map)
|
| 447 |
+
|
| 448 |
+
if (assign := field_info._original_assignment) is PydanticUndefined:
|
| 449 |
+
new_field = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS)
|
| 450 |
+
else:
|
| 451 |
+
new_field = FieldInfo_.from_annotated_attribute(ann, assign, _source=AnnotationSource.CLASS)
|
| 452 |
+
# The description might come from the docstring if `use_attribute_docstrings` was `True`:
|
| 453 |
+
new_field.description = new_field.description if new_field.description is not None else existing_desc
|
| 454 |
+
update_field_from_config(config_wrapper, f_name, new_field)
|
| 455 |
+
rebuilt_fields[f_name] = new_field
|
| 456 |
+
|
| 457 |
+
return rebuilt_fields
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def collect_dataclass_fields(
|
| 461 |
+
cls: type[StandardDataclass],
|
| 462 |
+
*,
|
| 463 |
+
config_wrapper: ConfigWrapper,
|
| 464 |
+
ns_resolver: NsResolver | None = None,
|
| 465 |
+
typevars_map: dict[Any, Any] | None = None,
|
| 466 |
+
) -> dict[str, FieldInfo]:
|
| 467 |
+
"""Collect the fields of a dataclass.
|
| 468 |
+
|
| 469 |
+
Args:
|
| 470 |
+
cls: dataclass.
|
| 471 |
+
config_wrapper: The config wrapper instance.
|
| 472 |
+
ns_resolver: Namespace resolver to use when getting dataclass annotations.
|
| 473 |
+
Defaults to an empty instance.
|
| 474 |
+
typevars_map: A dictionary mapping type variables to their concrete types.
|
| 475 |
+
|
| 476 |
+
Returns:
|
| 477 |
+
The dataclass fields.
|
| 478 |
+
"""
|
| 479 |
+
FieldInfo_ = import_cached_field_info()
|
| 480 |
+
|
| 481 |
+
fields: dict[str, FieldInfo] = {}
|
| 482 |
+
ns_resolver = ns_resolver or NsResolver()
|
| 483 |
+
dataclass_fields = cls.__dataclass_fields__
|
| 484 |
+
|
| 485 |
+
# The logic here is similar to `_typing_extra.get_cls_type_hints`,
|
| 486 |
+
# although we do it manually as stdlib dataclasses already have annotations
|
| 487 |
+
# collected in each class:
|
| 488 |
+
for base in reversed(cls.__mro__):
|
| 489 |
+
if not dataclasses.is_dataclass(base):
|
| 490 |
+
continue
|
| 491 |
+
|
| 492 |
+
with ns_resolver.push(base):
|
| 493 |
+
for ann_name, dataclass_field in dataclass_fields.items():
|
| 494 |
+
base_anns = _typing_extra.safe_get_annotations(base)
|
| 495 |
+
|
| 496 |
+
if ann_name not in base_anns:
|
| 497 |
+
# `__dataclass_fields__`contains every field, even the ones from base classes.
|
| 498 |
+
# Only collect the ones defined on `base`.
|
| 499 |
+
continue
|
| 500 |
+
|
| 501 |
+
globalns, localns = ns_resolver.types_namespace
|
| 502 |
+
ann_type, evaluated = _typing_extra.try_eval_type(dataclass_field.type, globalns, localns)
|
| 503 |
+
|
| 504 |
+
if _typing_extra.is_classvar_annotation(ann_type):
|
| 505 |
+
continue
|
| 506 |
+
|
| 507 |
+
if (
|
| 508 |
+
not dataclass_field.init
|
| 509 |
+
and dataclass_field.default is dataclasses.MISSING
|
| 510 |
+
and dataclass_field.default_factory is dataclasses.MISSING
|
| 511 |
+
):
|
| 512 |
+
# TODO: We should probably do something with this so that validate_assignment behaves properly
|
| 513 |
+
# Issue: https://github.com/pydantic/pydantic/issues/5470
|
| 514 |
+
continue
|
| 515 |
+
|
| 516 |
+
if isinstance(dataclass_field.default, FieldInfo_):
|
| 517 |
+
if dataclass_field.default.init_var:
|
| 518 |
+
if dataclass_field.default.init is False:
|
| 519 |
+
raise PydanticUserError(
|
| 520 |
+
f'Dataclass field {ann_name} has init=False and init_var=True, but these are mutually exclusive.',
|
| 521 |
+
code='clashing-init-and-init-var',
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
# TODO: same note as above re validate_assignment
|
| 525 |
+
continue
|
| 526 |
+
field_info = FieldInfo_.from_annotated_attribute(
|
| 527 |
+
ann_type, dataclass_field.default, _source=AnnotationSource.DATACLASS
|
| 528 |
+
)
|
| 529 |
+
field_info._original_assignment = dataclass_field.default
|
| 530 |
+
else:
|
| 531 |
+
field_info = FieldInfo_.from_annotated_attribute(
|
| 532 |
+
ann_type, dataclass_field, _source=AnnotationSource.DATACLASS
|
| 533 |
+
)
|
| 534 |
+
field_info._original_assignment = dataclass_field
|
| 535 |
+
|
| 536 |
+
if not evaluated:
|
| 537 |
+
field_info._complete = False
|
| 538 |
+
field_info._original_annotation = ann_type
|
| 539 |
+
|
| 540 |
+
fields[ann_name] = field_info
|
| 541 |
+
update_field_from_config(config_wrapper, ann_name, field_info)
|
| 542 |
+
|
| 543 |
+
if field_info.default is not PydanticUndefined and isinstance(
|
| 544 |
+
getattr(cls, ann_name, field_info), FieldInfo_
|
| 545 |
+
):
|
| 546 |
+
# We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo
|
| 547 |
+
setattr(cls, ann_name, field_info.default)
|
| 548 |
+
|
| 549 |
+
if typevars_map:
|
| 550 |
+
for field in fields.values():
|
| 551 |
+
# We don't pass any ns, as `field.annotation`
|
| 552 |
+
# was already evaluated. TODO: is this method relevant?
|
| 553 |
+
# Can't we juste use `_generics.replace_types`?
|
| 554 |
+
field.apply_typevars_map(typevars_map)
|
| 555 |
+
|
| 556 |
+
if config_wrapper.use_attribute_docstrings:
|
| 557 |
+
_update_fields_from_docstrings(
|
| 558 |
+
cls,
|
| 559 |
+
fields,
|
| 560 |
+
# We can't rely on the (more reliable) frame inspection method
|
| 561 |
+
# for stdlib dataclasses:
|
| 562 |
+
use_inspect=not hasattr(cls, '__is_pydantic_dataclass__'),
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
return fields
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def rebuild_dataclass_fields(
|
| 569 |
+
cls: type[PydanticDataclass],
|
| 570 |
+
*,
|
| 571 |
+
config_wrapper: ConfigWrapper,
|
| 572 |
+
ns_resolver: NsResolver,
|
| 573 |
+
typevars_map: Mapping[TypeVar, Any],
|
| 574 |
+
) -> dict[str, FieldInfo]:
|
| 575 |
+
"""Rebuild the (already present) dataclass fields by trying to reevaluate annotations.
|
| 576 |
+
|
| 577 |
+
This function should be called whenever a dataclass with incomplete fields is encountered.
|
| 578 |
+
|
| 579 |
+
Raises:
|
| 580 |
+
NameError: If one of the annotations failed to evaluate.
|
| 581 |
+
|
| 582 |
+
Note:
|
| 583 |
+
This function *doesn't* mutate the dataclass fields in place, as it can be called during
|
| 584 |
+
schema generation, where you don't want to mutate other dataclass's fields.
|
| 585 |
+
"""
|
| 586 |
+
FieldInfo_ = import_cached_field_info()
|
| 587 |
+
|
| 588 |
+
rebuilt_fields: dict[str, FieldInfo] = {}
|
| 589 |
+
with ns_resolver.push(cls):
|
| 590 |
+
for f_name, field_info in cls.__pydantic_fields__.items():
|
| 591 |
+
if field_info._complete:
|
| 592 |
+
rebuilt_fields[f_name] = field_info
|
| 593 |
+
else:
|
| 594 |
+
existing_desc = field_info.description
|
| 595 |
+
ann = _typing_extra.eval_type(
|
| 596 |
+
field_info._original_annotation,
|
| 597 |
+
*ns_resolver.types_namespace,
|
| 598 |
+
)
|
| 599 |
+
ann = _generics.replace_types(ann, typevars_map)
|
| 600 |
+
new_field = FieldInfo_.from_annotated_attribute(
|
| 601 |
+
ann,
|
| 602 |
+
field_info._original_assignment,
|
| 603 |
+
_source=AnnotationSource.DATACLASS,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
# The description might come from the docstring if `use_attribute_docstrings` was `True`:
|
| 607 |
+
new_field.description = new_field.description if new_field.description is not None else existing_desc
|
| 608 |
+
update_field_from_config(config_wrapper, f_name, new_field)
|
| 609 |
+
rebuilt_fields[f_name] = new_field
|
| 610 |
+
|
| 611 |
+
return rebuilt_fields
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def is_valid_field_name(name: str) -> bool:
|
| 615 |
+
return not name.startswith('_')
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def is_valid_privateattr_name(name: str) -> bool:
|
| 619 |
+
return name.startswith('_') and not name.startswith('__')
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def takes_validated_data_argument(
|
| 623 |
+
default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
|
| 624 |
+
) -> TypeIs[Callable[[dict[str, Any]], Any]]:
|
| 625 |
+
"""Whether the provided default factory callable has a validated data parameter."""
|
| 626 |
+
try:
|
| 627 |
+
sig = signature(default_factory)
|
| 628 |
+
except (ValueError, TypeError):
|
| 629 |
+
# `inspect.signature` might not be able to infer a signature, e.g. with C objects.
|
| 630 |
+
# In this case, we assume no data argument is present:
|
| 631 |
+
return False
|
| 632 |
+
|
| 633 |
+
parameters = list(sig.parameters.values())
|
| 634 |
+
|
| 635 |
+
return len(parameters) == 1 and can_be_positional(parameters[0]) and parameters[0].default is Parameter.empty
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_forward_ref.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Union
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class PydanticRecursiveRef:
|
| 9 |
+
type_ref: str
|
| 10 |
+
|
| 11 |
+
__name__ = 'PydanticRecursiveRef'
|
| 12 |
+
__hash__ = object.__hash__
|
| 13 |
+
|
| 14 |
+
def __call__(self) -> None:
|
| 15 |
+
"""Defining __call__ is necessary for the `typing` module to let you use an instance of
|
| 16 |
+
this class as the result of resolving a standard ForwardRef.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __or__(self, other):
|
| 20 |
+
return Union[self, other] # type: ignore
|
| 21 |
+
|
| 22 |
+
def __ror__(self, other):
|
| 23 |
+
return Union[other, self] # type: ignore
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/pkgs/pydantic-2.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import operator
|
| 4 |
+
import sys
|
| 5 |
+
import types
|
| 6 |
+
import typing
|
| 7 |
+
from collections import ChainMap
|
| 8 |
+
from collections.abc import Iterator, Mapping
|
| 9 |
+
from contextlib import contextmanager
|
| 10 |
+
from contextvars import ContextVar
|
| 11 |
+
from functools import reduce
|
| 12 |
+
from itertools import zip_longest
|
| 13 |
+
from types import prepare_class
|
| 14 |
+
from typing import TYPE_CHECKING, Annotated, Any, TypedDict, TypeVar, cast
|
| 15 |
+
from weakref import WeakValueDictionary
|
| 16 |
+
|
| 17 |
+
import typing_extensions
|
| 18 |
+
from typing_inspection import typing_objects
|
| 19 |
+
from typing_inspection.introspection import is_union_origin
|
| 20 |
+
|
| 21 |
+
from . import _typing_extra
|
| 22 |
+
from ._core_utils import get_type_ref
|
| 23 |
+
from ._forward_ref import PydanticRecursiveRef
|
| 24 |
+
from ._utils import all_identical, is_model_class
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from ..main import BaseModel
|
| 28 |
+
|
| 29 |
+
GenericTypesCacheKey = tuple[Any, Any, tuple[Any, ...]]
|
| 30 |
+
|
| 31 |
+
# Note: We want to remove LimitedDict, but to do this, we'd need to improve the handling of generics caching.
|
| 32 |
+
# Right now, to handle recursive generics, we some types must remain cached for brief periods without references.
|
| 33 |
+
# By chaining the WeakValuesDict with a LimitedDict, we have a way to retain caching for all types with references,
|
| 34 |
+
# while also retaining a limited number of types even without references. This is generally enough to build
|
| 35 |
+
# specific recursive generic models without losing required items out of the cache.
|
| 36 |
+
|
| 37 |
+
KT = TypeVar('KT')
|
| 38 |
+
VT = TypeVar('VT')
|
| 39 |
+
_LIMITED_DICT_SIZE = 100
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class LimitedDict(dict[KT, VT]):
|
| 43 |
+
def __init__(self, size_limit: int = _LIMITED_DICT_SIZE) -> None:
|
| 44 |
+
self.size_limit = size_limit
|
| 45 |
+
super().__init__()
|
| 46 |
+
|
| 47 |
+
def __setitem__(self, key: KT, value: VT, /) -> None:
|
| 48 |
+
super().__setitem__(key, value)
|
| 49 |
+
if len(self) > self.size_limit:
|
| 50 |
+
excess = len(self) - self.size_limit + self.size_limit // 10
|
| 51 |
+
to_remove = list(self.keys())[:excess]
|
| 52 |
+
for k in to_remove:
|
| 53 |
+
del self[k]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected
|
| 57 |
+
# once they are no longer referenced by the caller.
|
| 58 |
+
GenericTypesCache = WeakValueDictionary[GenericTypesCacheKey, 'type[BaseModel]']
|
| 59 |
+
|
| 60 |
+
if TYPE_CHECKING:
|
| 61 |
+
|
| 62 |
+
class DeepChainMap(ChainMap[KT, VT]): # type: ignore
|
| 63 |
+
...
|
| 64 |
+
|
| 65 |
+
else:
|
| 66 |
+
|
| 67 |
+
class DeepChainMap(ChainMap):
|
| 68 |
+
"""Variant of ChainMap that allows direct updates to inner scopes.
|
| 69 |
+
|
| 70 |
+
Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap,
|
| 71 |
+
with some light modifications for this use case.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def clear(self) -> None:
|
| 75 |
+
for mapping in self.maps:
|
| 76 |
+
mapping.clear()
|
| 77 |
+
|
| 78 |
+
def __setitem__(self, key: KT, value: VT) -> None:
|
| 79 |
+
for mapping in self.maps:
|
| 80 |
+
mapping[key] = value
|
| 81 |
+
|
| 82 |
+
def __delitem__(self, key: KT) -> None:
|
| 83 |
+
hit = False
|
| 84 |
+
for mapping in self.maps:
|
| 85 |
+
if key in mapping:
|
| 86 |
+
del mapping[key]
|
| 87 |
+
hit = True
|
| 88 |
+
if not hit:
|
| 89 |
+
raise KeyError(key)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Despite the fact that LimitedDict _seems_ no longer necessary, I'm very nervous to actually remove it
|
| 93 |
+
# and discover later on that we need to re-add all this infrastructure...
|
| 94 |
+
# _GENERIC_TYPES_CACHE = DeepChainMap(GenericTypesCache(), LimitedDict())
|
| 95 |
+
|
| 96 |
+
_GENERIC_TYPES_CACHE: ContextVar[GenericTypesCache | None] = ContextVar('_GENERIC_TYPES_CACHE', default=None)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class PydanticGenericMetadata(TypedDict):
|
| 100 |
+
origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__
|
| 101 |
+
args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__
|
| 102 |
+
parameters: tuple[TypeVar, ...] # analogous to typing.Generic.__parameters__
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def create_generic_submodel(
|
| 106 |
+
model_name: str, origin: type[BaseModel], args: tuple[Any, ...], params: tuple[Any, ...]
|
| 107 |
+
) -> type[BaseModel]:
|
| 108 |
+
"""Dynamically create a submodel of a provided (generic) BaseModel.
|
| 109 |
+
|
| 110 |
+
This is used when producing concrete parametrizations of generic models. This function
|
| 111 |
+
only *creates* the new subclass; the schema/validators/serialization must be updated to
|
| 112 |
+
reflect a concrete parametrization elsewhere.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
model_name: The name of the newly created model.
|
| 116 |
+
origin: The base class for the new model to inherit from.
|
| 117 |
+
args: A tuple of generic metadata arguments.
|
| 118 |
+
params: A tuple of generic metadata parameters.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
The created submodel.
|
| 122 |
+
"""
|
| 123 |
+
namespace: dict[str, Any] = {'__module__': origin.__module__}
|
| 124 |
+
bases = (origin,)
|
| 125 |
+
meta, ns, kwds = prepare_class(model_name, bases)
|
| 126 |
+
namespace.update(ns)
|
| 127 |
+
created_model = meta(
|
| 128 |
+
model_name,
|
| 129 |
+
bases,
|
| 130 |
+
namespace,
|
| 131 |
+
__pydantic_generic_metadata__={
|
| 132 |
+
'origin': origin,
|
| 133 |
+
'args': args,
|
| 134 |
+
'parameters': params,
|
| 135 |
+
},
|
| 136 |
+
__pydantic_reset_parent_namespace__=False,
|
| 137 |
+
**kwds,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
model_module, called_globally = _get_caller_frame_info(depth=3)
|
| 141 |
+
if called_globally: # create global reference and therefore allow pickling
|
| 142 |
+
object_by_reference = None
|
| 143 |
+
reference_name = model_name
|
| 144 |
+
reference_module_globals = sys.modules[created_model.__module__].__dict__
|
| 145 |
+
while object_by_reference is not created_model:
|
| 146 |
+
object_by_reference = reference_module_globals.setdefault(reference_name, created_model)
|
| 147 |
+
reference_name += '_'
|
| 148 |
+
|
| 149 |
+
return created_model
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _get_caller_frame_info(depth: int = 2) -> tuple[str | None, bool]:
|
| 153 |
+
"""Used inside a function to check whether it was called globally.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
depth: The depth to get the frame.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
A tuple contains `module_name` and `called_globally`.
|
| 160 |
+
|
| 161 |
+
Raises:
|
| 162 |
+
RuntimeError: If the function is not called inside a function.
|
| 163 |
+
"""
|
| 164 |
+
try:
|
| 165 |
+
previous_caller_frame = sys._getframe(depth)
|
| 166 |
+
except ValueError as e:
|
| 167 |
+
raise RuntimeError('This function must be used inside another function') from e
|
| 168 |
+
except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it
|
| 169 |
+
return None, False
|
| 170 |
+
frame_globals = previous_caller_frame.f_globals
|
| 171 |
+
return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
DictValues: type[Any] = {}.values().__class__
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def iter_contained_typevars(v: Any) -> Iterator[TypeVar]:
|
| 178 |
+
"""Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.
|
| 179 |
+
|
| 180 |
+
This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias,
|
| 181 |
+
since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list.
|
| 182 |
+
"""
|
| 183 |
+
if isinstance(v, TypeVar):
|
| 184 |
+
yield v
|
| 185 |
+
elif is_model_class(v):
|
| 186 |
+
yield from v.__pydantic_generic_metadata__['parameters']
|
| 187 |
+
elif isinstance(v, (DictValues, list)):
|
| 188 |
+
for var in v:
|
| 189 |
+
yield from iter_contained_typevars(var)
|
| 190 |
+
else:
|
| 191 |
+
args = get_args(v)
|
| 192 |
+
for arg in args:
|
| 193 |
+
yield from iter_contained_typevars(arg)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def get_args(v: Any) -> Any:
|
| 197 |
+
pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
|
| 198 |
+
if pydantic_generic_metadata:
|
| 199 |
+
return pydantic_generic_metadata.get('args')
|
| 200 |
+
return typing_extensions.get_args(v)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def get_origin(v: Any) -> Any:
|
| 204 |
+
pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
|
| 205 |
+
if pydantic_generic_metadata:
|
| 206 |
+
return pydantic_generic_metadata.get('origin')
|
| 207 |
+
return typing_extensions.get_origin(v)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def get_standard_typevars_map(cls: Any) -> dict[TypeVar, Any] | None:
|
| 211 |
+
"""Package a generic type's typevars and parametrization (if present) into a dictionary compatible with the
|
| 212 |
+
`replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias.
|
| 213 |
+
"""
|
| 214 |
+
origin = get_origin(cls)
|
| 215 |
+
if origin is None:
|
| 216 |
+
return None
|
| 217 |
+
if not hasattr(origin, '__parameters__'):
|
| 218 |
+
return None
|
| 219 |
+
|
| 220 |
+
# In this case, we know that cls is a _GenericAlias, and origin is the generic type
|
| 221 |
+
# So it is safe to access cls.__args__ and origin.__parameters__
|
| 222 |
+
args: tuple[Any, ...] = cls.__args__ # type: ignore
|
| 223 |
+
parameters: tuple[TypeVar, ...] = origin.__parameters__
|
| 224 |
+
return dict(zip(parameters, args))
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVar, Any]:
|
| 228 |
+
"""Package a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible
|
| 229 |
+
with the `replace_types` function.
|
| 230 |
+
|
| 231 |
+
Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is
|
| 232 |
+
stored in the __pydantic_generic_metadata__ attribute, we need special handling here.
|
| 233 |
+
"""
|
| 234 |
+
# TODO: This could be unified with `get_standard_typevars_map` if we stored the generic metadata
|
| 235 |
+
# in the __origin__, __args__, and __parameters__ attributes of the model.
|
| 236 |
+
generic_metadata = cls.__pydantic_generic_metadata__
|
| 237 |
+
origin = generic_metadata['origin']
|
| 238 |
+
args = generic_metadata['args']
|
| 239 |
+
if not args:
|
| 240 |
+
# No need to go into `iter_contained_typevars`:
|
| 241 |
+
return {}
|
| 242 |
+
return dict(zip(iter_contained_typevars(origin), args))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def replace_types(type_: Any, type_map: Mapping[TypeVar, Any] | None) -> Any:
|
| 246 |
+
"""Return type with all occurrences of `type_map` keys recursively replaced with their values.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
type_: The class or generic alias.
|
| 250 |
+
type_map: Mapping from `TypeVar` instance to concrete types.
|
| 251 |
+
|
| 252 |
+
Returns:
|
| 253 |
+
A new type representing the basic structure of `type_` with all
|
| 254 |
+
`typevar_map` keys recursively replaced.
|
| 255 |
+
|
| 256 |
+
Example:
|
| 257 |
+
```python
|
| 258 |
+
from typing import Union
|
| 259 |
+
|
| 260 |
+
from pydantic._internal._generics import replace_types
|
| 261 |
+
|
| 262 |
+
replace_types(tuple[str, Union[list[str], float]], {str: int})
|
| 263 |
+
#> tuple[int, Union[list[int], float]]
|
| 264 |
+
```
|
| 265 |
+
"""
|
| 266 |
+
if not type_map:
|
| 267 |
+
return type_
|
| 268 |
+
|
| 269 |
+
type_args = get_args(type_)
|
| 270 |
+
origin_type = get_origin(type_)
|
| 271 |
+
|
| 272 |
+
if typing_objects.is_annotated(origin_type):
|
| 273 |
+
annotated_type, *annotations = type_args
|
| 274 |
+
annotated_type = replace_types(annotated_type, type_map)
|
| 275 |
+
# TODO remove parentheses when we drop support for Python 3.10:
|
| 276 |
+
return Annotated[(annotated_type, *annotations)]
|
| 277 |
+
|
| 278 |
+
# Having type args is a good indicator that this is a typing special form
|
| 279 |
+
# instance or a generic alias of some sort.
|
| 280 |
+
if type_args:
|
| 281 |
+
resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args)
|
| 282 |
+
if all_identical(type_args, resolved_type_args):
|
| 283 |
+
# If all arguments are the same, there is no need to modify the
|
| 284 |
+
# type or create a new object at all
|
| 285 |
+
return type_
|
| 286 |
+
|
| 287 |
+
if (
|
| 288 |
+
origin_type is not None
|
| 289 |
+
and isinstance(type_, _typing_extra.typing_base)
|
| 290 |
+
and not isinstance(origin_type, _typing_extra.typing_base)
|
| 291 |
+
and getattr(type_, '_name', None) is not None
|
| 292 |
+
):
|
| 293 |
+
# In python < 3.9 generic aliases don't exist so any of these like `list`,
|
| 294 |
+
# `type` or `collections.abc.Callable` need to be translated.
|
| 295 |
+
# See: https://www.python.org/dev/peps/pep-0585
|
| 296 |
+
origin_type = getattr(typing, type_._name)
|
| 297 |
+
assert origin_type is not None
|
| 298 |
+
|
| 299 |
+
if is_union_origin(origin_type):
|
| 300 |
+
if any(typing_objects.is_any(arg) for arg in resolved_type_args):
|
| 301 |
+
# `Any | T` ~ `Any`:
|
| 302 |
+
resolved_type_args = (Any,)
|
| 303 |
+
# `Never | T` ~ `T`:
|
| 304 |
+
resolved_type_args = tuple(
|
| 305 |
+
arg
|
| 306 |
+
for arg in resolved_type_args
|
| 307 |
+
if not (typing_objects.is_noreturn(arg) or typing_objects.is_never(arg))
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# PEP-604 syntax (Ex.: list | str) is represented with a types.UnionType object that does not have __getitem__.
|
| 311 |
+
# We also cannot use isinstance() since we have to compare types.
|
| 312 |
+
if sys.version_info >= (3, 10) and origin_type is types.UnionType:
|
| 313 |
+
return reduce(operator.or_, resolved_type_args)
|
| 314 |
+
# NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below
|
| 315 |
+
return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]
|
| 316 |
+
|
| 317 |
+
# We handle pydantic generic models separately as they don't have the same
|
| 318 |
+
# semantics as "typing" classes or generic aliases
|
| 319 |
+
|
| 320 |
+
if not origin_type and is_model_class(type_):
|
| 321 |
+
parameters = type_.__pydantic_generic_metadata__['parameters']
|
| 322 |
+
if not parameters:
|
| 323 |
+
return type_
|
| 324 |
+
resolved_type_args = tuple(replace_types(t, type_map) for t in parameters)
|
| 325 |
+
if all_identical(parameters, resolved_type_args):
|
| 326 |
+
return type_
|
| 327 |
+
return type_[resolved_type_args]
|
| 328 |
+
|
| 329 |
+
# Handle special case for typehints that can have lists as arguments.
|
| 330 |
+
# `typing.Callable[[int, str], int]` is an example for this.
|
| 331 |
+
if isinstance(type_, list):
|
| 332 |
+
resolved_list = [replace_types(element, type_map) for element in type_]
|
| 333 |
+
if all_identical(type_, resolved_list):
|
| 334 |
+
return type_
|
| 335 |
+
return resolved_list
|
| 336 |
+
|
| 337 |
+
# If all else fails, we try to resolve the type directly and otherwise just
|
| 338 |
+
# return the input with no modifications.
|
| 339 |
+
return type_map.get(type_, type_)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
|
| 343 |
+
"""Return a mapping between the parameters of a generic model and the provided arguments during parameterization.
|
| 344 |
+
|
| 345 |
+
Raises:
|
| 346 |
+
TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).
|
| 347 |
+
|
| 348 |
+
Example:
|
| 349 |
+
```python {test="skip" lint="skip"}
|
| 350 |
+
class Model[T, U, V = int](BaseModel): ...
|
| 351 |
+
|
| 352 |
+
map_generic_model_arguments(Model, (str, bytes))
|
| 353 |
+
#> {T: str, U: bytes, V: int}
|
| 354 |
+
|
| 355 |
+
map_generic_model_arguments(Model, (str,))
|
| 356 |
+
#> TypeError: Too few arguments for <class '__main__.Model'>; actual 1, expected at least 2
|
| 357 |
+
|
| 358 |
+
map_generic_model_arguments(Model, (str, bytes, int, complex))
|
| 359 |
+
#> TypeError: Too many arguments for <class '__main__.Model'>; actual 4, expected 3
|
| 360 |
+
```
|
| 361 |
+
|
| 362 |
+
Note:
|
| 363 |
+
This function is analogous to the private `typing._check_generic_specialization` function.
|
| 364 |
+
"""
|
| 365 |
+
parameters = cls.__pydantic_generic_metadata__['parameters']
|
| 366 |
+
expected_len = len(parameters)
|
| 367 |
+
typevars_map: dict[TypeVar, Any] = {}
|
| 368 |
+
|
| 369 |
+
_missing = object()
|
| 370 |
+
for parameter, argument in zip_longest(parameters, args, fillvalue=_missing):
|
| 371 |
+
if parameter is _missing:
|
| 372 |
+
raise TypeError(f'Too many arguments for {cls}; actual {len(args)}, expected {expected_len}')
|
| 373 |
+
|
| 374 |
+
if argument is _missing:
|
| 375 |
+
param = cast(TypeVar, parameter)
|
| 376 |
+
try:
|
| 377 |
+
has_default = param.has_default() # pyright: ignore[reportAttributeAccessIssue]
|
| 378 |
+
except AttributeError:
|
| 379 |
+
# Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13.
|
| 380 |
+
has_default = False
|
| 381 |
+
if has_default:
|
| 382 |
+
# The default might refer to other type parameters. For an example, see:
|
| 383 |
+
# https://typing.python.org/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics
|
| 384 |
+
typevars_map[param] = replace_types(param.__default__, typevars_map) # pyright: ignore[reportAttributeAccessIssue]
|
| 385 |
+
else:
|
| 386 |
+
expected_len -= sum(hasattr(p, 'has_default') and p.has_default() for p in parameters) # pyright: ignore[reportAttributeAccessIssue]
|
| 387 |
+
raise TypeError(f'Too few arguments for {cls}; actual {len(args)}, expected at least {expected_len}')
|
| 388 |
+
else:
|
| 389 |
+
param = cast(TypeVar, parameter)
|
| 390 |
+
typevars_map[param] = argument
|
| 391 |
+
|
| 392 |
+
return typevars_map
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
_generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
@contextmanager
|
| 399 |
+
def generic_recursion_self_type(
|
| 400 |
+
origin: type[BaseModel], args: tuple[Any, ...]
|
| 401 |
+
) -> Iterator[PydanticRecursiveRef | None]:
|
| 402 |
+
"""This contextmanager should be placed around the recursive calls used to build a generic type,
|
| 403 |
+
and accept as arguments the generic origin type and the type arguments being passed to it.
|
| 404 |
+
|
| 405 |
+
If the same origin and arguments are observed twice, it implies that a self-reference placeholder
|
| 406 |
+
can be used while building the core schema, and will produce a schema_ref that will be valid in the
|
| 407 |
+
final parent schema.
|
| 408 |
+
"""
|
| 409 |
+
previously_seen_type_refs = _generic_recursion_cache.get()
|
| 410 |
+
if previously_seen_type_refs is None:
|
| 411 |
+
previously_seen_type_refs = set()
|
| 412 |
+
token = _generic_recursion_cache.set(previously_seen_type_refs)
|
| 413 |
+
else:
|
| 414 |
+
token = None
|
| 415 |
+
|
| 416 |
+
try:
|
| 417 |
+
type_ref = get_type_ref(origin, args_override=args)
|
| 418 |
+
if type_ref in previously_seen_type_refs:
|
| 419 |
+
self_type = PydanticRecursiveRef(type_ref=type_ref)
|
| 420 |
+
yield self_type
|
| 421 |
+
else:
|
| 422 |
+
previously_seen_type_refs.add(type_ref)
|
| 423 |
+
yield
|
| 424 |
+
previously_seen_type_refs.remove(type_ref)
|
| 425 |
+
finally:
|
| 426 |
+
if token:
|
| 427 |
+
_generic_recursion_cache.reset(token)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def recursively_defined_type_refs() -> set[str]:
|
| 431 |
+
visited = _generic_recursion_cache.get()
|
| 432 |
+
if not visited:
|
| 433 |
+
return set() # not in a generic recursion, so there are no types
|
| 434 |
+
|
| 435 |
+
return visited.copy() # don't allow modifications
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None:
|
| 439 |
+
"""The use of a two-stage cache lookup approach was necessary to have the highest performance possible for
|
| 440 |
+
repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime),
|
| 441 |
+
while still ensuring that certain alternative parametrizations ultimately resolve to the same type.
|
| 442 |
+
|
| 443 |
+
As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]].
|
| 444 |
+
The approach could be modified to not use two different cache keys at different points, but the
|
| 445 |
+
_early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the
|
| 446 |
+
_late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the
|
| 447 |
+
same after resolving the type arguments will always produce cache hits.
|
| 448 |
+
|
| 449 |
+
If we wanted to move to only using a single cache key per type, we would either need to always use the
|
| 450 |
+
slower/more computationally intensive logic associated with _late_cache_key, or would need to accept
|
| 451 |
+
that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships
|
| 452 |
+
during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually
|
| 453 |
+
equal.
|
| 454 |
+
"""
|
| 455 |
+
generic_types_cache = _GENERIC_TYPES_CACHE.get()
|
| 456 |
+
if generic_types_cache is None:
|
| 457 |
+
generic_types_cache = GenericTypesCache()
|
| 458 |
+
_GENERIC_TYPES_CACHE.set(generic_types_cache)
|
| 459 |
+
return generic_types_cache.get(_early_cache_key(parent, typevar_values))
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def get_cached_generic_type_late(
|
| 463 |
+
parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...]
|
| 464 |
+
) -> type[BaseModel] | None:
|
| 465 |
+
"""See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup."""
|
| 466 |
+
generic_types_cache = _GENERIC_TYPES_CACHE.get()
|
| 467 |
+
if (
|
| 468 |
+
generic_types_cache is None
|
| 469 |
+
): # pragma: no cover (early cache is guaranteed to run first and initialize the cache)
|
| 470 |
+
generic_types_cache = GenericTypesCache()
|
| 471 |
+
_GENERIC_TYPES_CACHE.set(generic_types_cache)
|
| 472 |
+
cached = generic_types_cache.get(_late_cache_key(origin, args, typevar_values))
|
| 473 |
+
if cached is not None:
|
| 474 |
+
set_cached_generic_type(parent, typevar_values, cached, origin, args)
|
| 475 |
+
return cached
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def set_cached_generic_type(
|
| 479 |
+
parent: type[BaseModel],
|
| 480 |
+
typevar_values: tuple[Any, ...],
|
| 481 |
+
type_: type[BaseModel],
|
| 482 |
+
origin: type[BaseModel] | None = None,
|
| 483 |
+
args: tuple[Any, ...] | None = None,
|
| 484 |
+
) -> None:
|
| 485 |
+
"""See the docstring of `get_cached_generic_type_early` for more information about why items are cached with
|
| 486 |
+
two different keys.
|
| 487 |
+
"""
|
| 488 |
+
generic_types_cache = _GENERIC_TYPES_CACHE.get()
|
| 489 |
+
if (
|
| 490 |
+
generic_types_cache is None
|
| 491 |
+
): # pragma: no cover (cache lookup is guaranteed to run first and initialize the cache)
|
| 492 |
+
generic_types_cache = GenericTypesCache()
|
| 493 |
+
_GENERIC_TYPES_CACHE.set(generic_types_cache)
|
| 494 |
+
generic_types_cache[_early_cache_key(parent, typevar_values)] = type_
|
| 495 |
+
if len(typevar_values) == 1:
|
| 496 |
+
generic_types_cache[_early_cache_key(parent, typevar_values[0])] = type_
|
| 497 |
+
if origin and args:
|
| 498 |
+
generic_types_cache[_late_cache_key(origin, args, typevar_values)] = type_
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def _union_orderings_key(typevar_values: Any) -> Any:
|
| 502 |
+
"""This is intended to help differentiate between Union types with the same arguments in different order.
|
| 503 |
+
|
| 504 |
+
Thanks to caching internal to the `typing` module, it is not possible to distinguish between
|
| 505 |
+
List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List)
|
| 506 |
+
because `typing` considers Union[int, float] to be equal to Union[float, int].
|
| 507 |
+
|
| 508 |
+
However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int].
|
| 509 |
+
Because we parse items as the first Union type that is successful, we get slightly more consistent behavior
|
| 510 |
+
if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_
|
| 511 |
+
get the exact-correct order of items in the union, but that would require a change to the `typing` module itself.
|
| 512 |
+
(See https://github.com/python/cpython/issues/86483 for reference.)
|
| 513 |
+
"""
|
| 514 |
+
if isinstance(typevar_values, tuple):
|
| 515 |
+
return tuple(_union_orderings_key(value) for value in typevar_values)
|
| 516 |
+
elif typing_objects.is_union(typing_extensions.get_origin(typevar_values)):
|
| 517 |
+
return get_args(typevar_values)
|
| 518 |
+
else:
|
| 519 |
+
return ()
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey:
|
| 523 |
+
"""This is intended for minimal computational overhead during lookups of cached types.
|
| 524 |
+
|
| 525 |
+
Note that this is overly simplistic, and it's possible that two different cls/typevar_values
|
| 526 |
+
inputs would ultimately result in the same type being created in BaseModel.__class_getitem__.
|
| 527 |
+
To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key
|
| 528 |
+
lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__
|
| 529 |
+
would result in the same type.
|
| 530 |
+
"""
|
| 531 |
+
return cls, typevar_values, _union_orderings_key(typevar_values)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey:
|
| 535 |
+
"""This is intended for use later in the process of creating a new type, when we have more information
|
| 536 |
+
about the exact args that will be passed. If it turns out that a different set of inputs to
|
| 537 |
+
__class_getitem__ resulted in the same inputs to the generic type creation process, we can still
|
| 538 |
+
return the cached type, and update the cache with the _early_cache_key as well.
|
| 539 |
+
"""
|
| 540 |
+
# The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an
|
| 541 |
+
# _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key,
|
| 542 |
+
# whereas this function will always produce a tuple as the first item in the key.
|
| 543 |
+
return _union_orderings_key(typevar_values), origin, args
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_git.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Git utilities, adopted from mypy's git utilities (https://github.com/python/mypy/blob/master/mypy/git.py)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import subprocess
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def is_git_repo(dir: Path) -> bool:
|
| 10 |
+
"""Is the given directory version-controlled with git?"""
|
| 11 |
+
return dir.joinpath('.git').exists()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def have_git() -> bool: # pragma: no cover
|
| 15 |
+
"""Can we run the git executable?"""
|
| 16 |
+
try:
|
| 17 |
+
subprocess.check_output(['git', '--help'])
|
| 18 |
+
return True
|
| 19 |
+
except subprocess.CalledProcessError:
|
| 20 |
+
return False
|
| 21 |
+
except OSError:
|
| 22 |
+
return False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def git_revision(dir: Path) -> str:
|
| 26 |
+
"""Get the SHA-1 of the HEAD of a git repository."""
|
| 27 |
+
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=dir).decode('utf-8').strip()
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_import_utils.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import cache
|
| 2 |
+
from typing import TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
if TYPE_CHECKING:
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from pydantic.fields import FieldInfo
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@cache
|
| 10 |
+
def import_cached_base_model() -> type['BaseModel']:
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
return BaseModel
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@cache
|
| 17 |
+
def import_cached_field_info() -> type['FieldInfo']:
|
| 18 |
+
from pydantic.fields import FieldInfo
|
| 19 |
+
|
| 20 |
+
return FieldInfo
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_internal_dataclass.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
# `slots` is available on Python >= 3.10
|
| 4 |
+
if sys.version_info >= (3, 10):
|
| 5 |
+
slots_true = {'slots': True}
|
| 6 |
+
else:
|
| 7 |
+
slots_true = {}
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_known_annotated_metadata.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from collections.abc import Iterable
|
| 5 |
+
from copy import copy
|
| 6 |
+
from functools import lru_cache, partial
|
| 7 |
+
from typing import TYPE_CHECKING, Any
|
| 8 |
+
|
| 9 |
+
from pydantic_core import CoreSchema, PydanticCustomError, ValidationError, to_jsonable_python
|
| 10 |
+
from pydantic_core import core_schema as cs
|
| 11 |
+
|
| 12 |
+
from ._fields import PydanticMetadata
|
| 13 |
+
from ._import_utils import import_cached_field_info
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
STRICT = {'strict'}
|
| 19 |
+
FAIL_FAST = {'fail_fast'}
|
| 20 |
+
LENGTH_CONSTRAINTS = {'min_length', 'max_length'}
|
| 21 |
+
INEQUALITY = {'le', 'ge', 'lt', 'gt'}
|
| 22 |
+
NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY}
|
| 23 |
+
ALLOW_INF_NAN = {'allow_inf_nan'}
|
| 24 |
+
|
| 25 |
+
STR_CONSTRAINTS = {
|
| 26 |
+
*LENGTH_CONSTRAINTS,
|
| 27 |
+
*STRICT,
|
| 28 |
+
'strip_whitespace',
|
| 29 |
+
'to_lower',
|
| 30 |
+
'to_upper',
|
| 31 |
+
'pattern',
|
| 32 |
+
'coerce_numbers_to_str',
|
| 33 |
+
}
|
| 34 |
+
BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
|
| 35 |
+
|
| 36 |
+
LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
|
| 37 |
+
TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
|
| 38 |
+
SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
|
| 39 |
+
DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
|
| 40 |
+
GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
|
| 41 |
+
SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}
|
| 42 |
+
|
| 43 |
+
FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
|
| 44 |
+
DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}
|
| 45 |
+
INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
|
| 46 |
+
BOOL_CONSTRAINTS = STRICT
|
| 47 |
+
UUID_CONSTRAINTS = STRICT
|
| 48 |
+
|
| 49 |
+
DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
|
| 50 |
+
TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
|
| 51 |
+
TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
|
| 52 |
+
LAX_OR_STRICT_CONSTRAINTS = STRICT
|
| 53 |
+
ENUM_CONSTRAINTS = STRICT
|
| 54 |
+
COMPLEX_CONSTRAINTS = STRICT
|
| 55 |
+
|
| 56 |
+
UNION_CONSTRAINTS = {'union_mode'}
|
| 57 |
+
URL_CONSTRAINTS = {
|
| 58 |
+
'max_length',
|
| 59 |
+
'allowed_schemes',
|
| 60 |
+
'host_required',
|
| 61 |
+
'default_host',
|
| 62 |
+
'default_port',
|
| 63 |
+
'default_path',
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url')
|
| 67 |
+
SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES)
|
| 68 |
+
NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime')
|
| 69 |
+
|
| 70 |
+
CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set)
|
| 71 |
+
|
| 72 |
+
constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [
|
| 73 |
+
(STR_CONSTRAINTS, TEXT_SCHEMA_TYPES),
|
| 74 |
+
(BYTES_CONSTRAINTS, ('bytes',)),
|
| 75 |
+
(LIST_CONSTRAINTS, ('list',)),
|
| 76 |
+
(TUPLE_CONSTRAINTS, ('tuple',)),
|
| 77 |
+
(SET_CONSTRAINTS, ('set', 'frozenset')),
|
| 78 |
+
(DICT_CONSTRAINTS, ('dict',)),
|
| 79 |
+
(GENERATOR_CONSTRAINTS, ('generator',)),
|
| 80 |
+
(FLOAT_CONSTRAINTS, ('float',)),
|
| 81 |
+
(INT_CONSTRAINTS, ('int',)),
|
| 82 |
+
(DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime', 'timedelta')),
|
| 83 |
+
# TODO: this is a bit redundant, we could probably avoid some of these
|
| 84 |
+
(STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')),
|
| 85 |
+
(UNION_CONSTRAINTS, ('union',)),
|
| 86 |
+
(URL_CONSTRAINTS, ('url', 'multi-host-url')),
|
| 87 |
+
(BOOL_CONSTRAINTS, ('bool',)),
|
| 88 |
+
(UUID_CONSTRAINTS, ('uuid',)),
|
| 89 |
+
(LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
|
| 90 |
+
(ENUM_CONSTRAINTS, ('enum',)),
|
| 91 |
+
(DECIMAL_CONSTRAINTS, ('decimal',)),
|
| 92 |
+
(COMPLEX_CONSTRAINTS, ('complex',)),
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
for constraints, schemas in constraint_schema_pairings:
|
| 96 |
+
for c in constraints:
|
| 97 |
+
CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def as_jsonable_value(v: Any) -> Any:
|
| 101 |
+
if type(v) not in (int, str, float, bytes, bool, type(None)):
|
| 102 |
+
return to_jsonable_python(v)
|
| 103 |
+
return v
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]:
|
| 107 |
+
"""Expand the annotations.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
annotations: An iterable of annotations.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
An iterable of expanded annotations.
|
| 114 |
+
|
| 115 |
+
Example:
|
| 116 |
+
```python
|
| 117 |
+
from annotated_types import Ge, Len
|
| 118 |
+
|
| 119 |
+
from pydantic._internal._known_annotated_metadata import expand_grouped_metadata
|
| 120 |
+
|
| 121 |
+
print(list(expand_grouped_metadata([Ge(4), Len(5)])))
|
| 122 |
+
#> [Ge(ge=4), MinLen(min_length=5)]
|
| 123 |
+
```
|
| 124 |
+
"""
|
| 125 |
+
import annotated_types as at
|
| 126 |
+
|
| 127 |
+
FieldInfo = import_cached_field_info()
|
| 128 |
+
|
| 129 |
+
for annotation in annotations:
|
| 130 |
+
if isinstance(annotation, at.GroupedMetadata):
|
| 131 |
+
yield from annotation
|
| 132 |
+
elif isinstance(annotation, FieldInfo):
|
| 133 |
+
yield from annotation.metadata
|
| 134 |
+
# this is a bit problematic in that it results in duplicate metadata
|
| 135 |
+
# all of our "consumers" can handle it, but it is not ideal
|
| 136 |
+
# we probably should split up FieldInfo into:
|
| 137 |
+
# - annotated types metadata
|
| 138 |
+
# - individual metadata known only to Pydantic
|
| 139 |
+
annotation = copy(annotation)
|
| 140 |
+
annotation.metadata = []
|
| 141 |
+
yield annotation
|
| 142 |
+
else:
|
| 143 |
+
yield annotation
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@lru_cache
|
| 147 |
+
def _get_at_to_constraint_map() -> dict[type, str]:
|
| 148 |
+
"""Return a mapping of annotated types to constraints.
|
| 149 |
+
|
| 150 |
+
Normally, we would define a mapping like this in the module scope, but we can't do that
|
| 151 |
+
because we don't permit module level imports of `annotated_types`, in an attempt to speed up
|
| 152 |
+
the import time of `pydantic`. We still only want to have this dictionary defined in one place,
|
| 153 |
+
so we use this function to cache the result.
|
| 154 |
+
"""
|
| 155 |
+
import annotated_types as at
|
| 156 |
+
|
| 157 |
+
return {
|
| 158 |
+
at.Gt: 'gt',
|
| 159 |
+
at.Ge: 'ge',
|
| 160 |
+
at.Lt: 'lt',
|
| 161 |
+
at.Le: 'le',
|
| 162 |
+
at.MultipleOf: 'multiple_of',
|
| 163 |
+
at.MinLen: 'min_length',
|
| 164 |
+
at.MaxLen: 'max_length',
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901
|
| 169 |
+
"""Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
|
| 170 |
+
Otherwise return `None`.
|
| 171 |
+
|
| 172 |
+
This does not handle all known annotations. If / when it does, it can always
|
| 173 |
+
return a CoreSchema and return the unmodified schema if the annotation should be ignored.
|
| 174 |
+
|
| 175 |
+
Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
annotation: The annotation.
|
| 179 |
+
schema: The schema.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
An updated schema with annotation if it is an annotation we know about, `None` otherwise.
|
| 183 |
+
|
| 184 |
+
Raises:
|
| 185 |
+
RuntimeError: If a constraint can't be applied to a specific schema type.
|
| 186 |
+
ValueError: If an unknown constraint is encountered.
|
| 187 |
+
"""
|
| 188 |
+
import annotated_types as at
|
| 189 |
+
|
| 190 |
+
from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check
|
| 191 |
+
|
| 192 |
+
schema = schema.copy()
|
| 193 |
+
schema_update, other_metadata = collect_known_metadata([annotation])
|
| 194 |
+
schema_type = schema['type']
|
| 195 |
+
|
| 196 |
+
chain_schema_constraints: set[str] = {
|
| 197 |
+
'pattern',
|
| 198 |
+
'strip_whitespace',
|
| 199 |
+
'to_lower',
|
| 200 |
+
'to_upper',
|
| 201 |
+
'coerce_numbers_to_str',
|
| 202 |
+
}
|
| 203 |
+
chain_schema_steps: list[CoreSchema] = []
|
| 204 |
+
|
| 205 |
+
for constraint, value in schema_update.items():
|
| 206 |
+
if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS:
|
| 207 |
+
raise ValueError(f'Unknown constraint {constraint}')
|
| 208 |
+
allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]
|
| 209 |
+
|
| 210 |
+
# if it becomes necessary to handle more than one constraint
|
| 211 |
+
# in this recursive case with function-after or function-wrap, we should refactor
|
| 212 |
+
# this is a bit challenging because we sometimes want to apply constraints to the inner schema,
|
| 213 |
+
# whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
|
| 214 |
+
if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
|
| 215 |
+
schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function schema
|
| 216 |
+
return schema
|
| 217 |
+
|
| 218 |
+
# if we're allowed to apply constraint directly to the schema, like le to int, do that
|
| 219 |
+
if schema_type in allowed_schemas:
|
| 220 |
+
if constraint == 'union_mode' and schema_type == 'union':
|
| 221 |
+
schema['mode'] = value # type: ignore # schema is UnionSchema
|
| 222 |
+
else:
|
| 223 |
+
schema[constraint] = value
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
# else, apply a function after validator to the schema to enforce the corresponding constraint
|
| 227 |
+
if constraint in chain_schema_constraints:
|
| 228 |
+
|
| 229 |
+
def _apply_constraint_with_incompatibility_info(
|
| 230 |
+
value: Any, handler: cs.ValidatorFunctionWrapHandler
|
| 231 |
+
) -> Any:
|
| 232 |
+
try:
|
| 233 |
+
x = handler(value)
|
| 234 |
+
except ValidationError as ve:
|
| 235 |
+
# if the error is about the type, it's likely that the constraint is incompatible the type of the field
|
| 236 |
+
# for example, the following invalid schema wouldn't be caught during schema build, but rather at this point
|
| 237 |
+
# with a cryptic 'string_type' error coming from the string validator,
|
| 238 |
+
# that we'd rather express as a constraint incompatibility error (TypeError)
|
| 239 |
+
# Annotated[list[int], Field(pattern='abc')]
|
| 240 |
+
if 'type' in ve.errors()[0]['type']:
|
| 241 |
+
raise TypeError(
|
| 242 |
+
f"Unable to apply constraint '{constraint}' to supplied value {value} for schema of type '{schema_type}'" # noqa: B023
|
| 243 |
+
)
|
| 244 |
+
raise ve
|
| 245 |
+
return x
|
| 246 |
+
|
| 247 |
+
chain_schema_steps.append(
|
| 248 |
+
cs.no_info_wrap_validator_function(
|
| 249 |
+
_apply_constraint_with_incompatibility_info, cs.str_schema(**{constraint: value})
|
| 250 |
+
)
|
| 251 |
+
)
|
| 252 |
+
elif constraint in NUMERIC_VALIDATOR_LOOKUP:
|
| 253 |
+
if constraint in LENGTH_CONSTRAINTS:
|
| 254 |
+
inner_schema = schema
|
| 255 |
+
while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:
|
| 256 |
+
inner_schema = inner_schema['schema'] # type: ignore
|
| 257 |
+
inner_schema_type = inner_schema['type']
|
| 258 |
+
if inner_schema_type == 'list' or (
|
| 259 |
+
inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
|
| 260 |
+
):
|
| 261 |
+
js_constraint_key = 'minItems' if constraint == 'min_length' else 'maxItems'
|
| 262 |
+
else:
|
| 263 |
+
js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'
|
| 264 |
+
else:
|
| 265 |
+
js_constraint_key = constraint
|
| 266 |
+
|
| 267 |
+
schema = cs.no_info_after_validator_function(
|
| 268 |
+
partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema
|
| 269 |
+
)
|
| 270 |
+
metadata = schema.get('metadata', {})
|
| 271 |
+
if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:
|
| 272 |
+
metadata['pydantic_js_updates'] = {
|
| 273 |
+
**existing_json_schema_updates,
|
| 274 |
+
**{js_constraint_key: as_jsonable_value(value)},
|
| 275 |
+
}
|
| 276 |
+
else:
|
| 277 |
+
metadata['pydantic_js_updates'] = {js_constraint_key: as_jsonable_value(value)}
|
| 278 |
+
schema['metadata'] = metadata
|
| 279 |
+
elif constraint == 'allow_inf_nan' and value is False:
|
| 280 |
+
schema = cs.no_info_after_validator_function(
|
| 281 |
+
forbid_inf_nan_check,
|
| 282 |
+
schema,
|
| 283 |
+
)
|
| 284 |
+
else:
|
| 285 |
+
# It's rare that we'd get here, but it's possible if we add a new constraint and forget to handle it
|
| 286 |
+
# Most constraint errors are caught at runtime during attempted application
|
| 287 |
+
raise RuntimeError(f"Unable to apply constraint '{constraint}' to schema of type '{schema_type}'")
|
| 288 |
+
|
| 289 |
+
for annotation in other_metadata:
|
| 290 |
+
if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
|
| 291 |
+
constraint = at_to_constraint_map[annotation_type]
|
| 292 |
+
validator = NUMERIC_VALIDATOR_LOOKUP.get(constraint)
|
| 293 |
+
if validator is None:
|
| 294 |
+
raise ValueError(f'Unknown constraint {constraint}')
|
| 295 |
+
schema = cs.no_info_after_validator_function(
|
| 296 |
+
partial(validator, {constraint: getattr(annotation, constraint)}), schema
|
| 297 |
+
)
|
| 298 |
+
continue
|
| 299 |
+
elif isinstance(annotation, (at.Predicate, at.Not)):
|
| 300 |
+
predicate_name = f'{annotation.func.__qualname__!r} ' if hasattr(annotation.func, '__qualname__') else ''
|
| 301 |
+
|
| 302 |
+
# Note: B023 is ignored because even though we iterate over `other_metadata`, it is guaranteed
|
| 303 |
+
# to be of length 1. `apply_known_metadata()` is called from `GenerateSchema`, where annotations
|
| 304 |
+
# were already expanded via `expand_grouped_metadata()`. Confusing, but this falls into the annotations
|
| 305 |
+
# refactor.
|
| 306 |
+
if isinstance(annotation, at.Predicate):
|
| 307 |
+
|
| 308 |
+
def val_func(v: Any) -> Any:
|
| 309 |
+
predicate_satisfied = annotation.func(v) # noqa: B023
|
| 310 |
+
if not predicate_satisfied:
|
| 311 |
+
raise PydanticCustomError(
|
| 312 |
+
'predicate_failed',
|
| 313 |
+
f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
|
| 314 |
+
)
|
| 315 |
+
return v
|
| 316 |
+
|
| 317 |
+
else:
|
| 318 |
+
|
| 319 |
+
def val_func(v: Any) -> Any:
|
| 320 |
+
predicate_satisfied = annotation.func(v) # noqa: B023
|
| 321 |
+
if predicate_satisfied:
|
| 322 |
+
raise PydanticCustomError(
|
| 323 |
+
'not_operation_failed',
|
| 324 |
+
f'Not of {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
|
| 325 |
+
)
|
| 326 |
+
return v
|
| 327 |
+
|
| 328 |
+
schema = cs.no_info_after_validator_function(val_func, schema)
|
| 329 |
+
else:
|
| 330 |
+
# ignore any other unknown metadata
|
| 331 |
+
return None
|
| 332 |
+
|
| 333 |
+
if chain_schema_steps:
|
| 334 |
+
chain_schema_steps = [schema] + chain_schema_steps
|
| 335 |
+
return cs.chain_schema(chain_schema_steps)
|
| 336 |
+
|
| 337 |
+
return schema
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]:
|
| 341 |
+
"""Split `annotations` into known metadata and unknown annotations.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
annotations: An iterable of annotations.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
A tuple contains a dict of known metadata and a list of unknown annotations.
|
| 348 |
+
|
| 349 |
+
Example:
|
| 350 |
+
```python
|
| 351 |
+
from annotated_types import Gt, Len
|
| 352 |
+
|
| 353 |
+
from pydantic._internal._known_annotated_metadata import collect_known_metadata
|
| 354 |
+
|
| 355 |
+
print(collect_known_metadata([Gt(1), Len(42), ...]))
|
| 356 |
+
#> ({'gt': 1, 'min_length': 42}, [Ellipsis])
|
| 357 |
+
```
|
| 358 |
+
"""
|
| 359 |
+
annotations = expand_grouped_metadata(annotations)
|
| 360 |
+
|
| 361 |
+
res: dict[str, Any] = {}
|
| 362 |
+
remaining: list[Any] = []
|
| 363 |
+
|
| 364 |
+
for annotation in annotations:
|
| 365 |
+
# isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
|
| 366 |
+
if isinstance(annotation, PydanticMetadata):
|
| 367 |
+
res.update(annotation.__dict__)
|
| 368 |
+
# we don't use dataclasses.asdict because that recursively calls asdict on the field values
|
| 369 |
+
elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
|
| 370 |
+
constraint = at_to_constraint_map[annotation_type]
|
| 371 |
+
res[constraint] = getattr(annotation, constraint)
|
| 372 |
+
elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata):
|
| 373 |
+
# also support PydanticMetadata classes being used without initialisation,
|
| 374 |
+
# e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
|
| 375 |
+
res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')})
|
| 376 |
+
else:
|
| 377 |
+
remaining.append(annotation)
|
| 378 |
+
# Nones can sneak in but pydantic-core will reject them
|
| 379 |
+
# it'd be nice to clean things up so we don't put in None (we probably don't _need_ to, it was just easier)
|
| 380 |
+
# but this is simple enough to kick that can down the road
|
| 381 |
+
res = {k: v for k, v in res.items() if v is not None}
|
| 382 |
+
return res, remaining
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None:
|
| 386 |
+
"""A small utility function to validate that the given metadata can be applied to the target.
|
| 387 |
+
More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
|
| 388 |
+
|
| 389 |
+
Args:
|
| 390 |
+
metadata: A dict of metadata.
|
| 391 |
+
allowed: An iterable of allowed metadata.
|
| 392 |
+
source_type: The source type.
|
| 393 |
+
|
| 394 |
+
Raises:
|
| 395 |
+
TypeError: If there is metadatas that can't be applied on source type.
|
| 396 |
+
"""
|
| 397 |
+
unknown = metadata.keys() - set(allowed)
|
| 398 |
+
if unknown:
|
| 399 |
+
raise TypeError(
|
| 400 |
+
f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
|
| 401 |
+
)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_mock_val_ser.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Iterator, Mapping
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, TypeVar, Union
|
| 5 |
+
|
| 6 |
+
from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
|
| 7 |
+
|
| 8 |
+
from ..errors import PydanticErrorCodes, PydanticUserError
|
| 9 |
+
from ..plugin._schema_validator import PluggableSchemaValidator
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from ..dataclasses import PydanticDataclass
|
| 13 |
+
from ..main import BaseModel
|
| 14 |
+
from ..type_adapter import TypeAdapter
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
ValSer = TypeVar('ValSer', bound=Union[SchemaValidator, PluggableSchemaValidator, SchemaSerializer])
|
| 18 |
+
T = TypeVar('T')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MockCoreSchema(Mapping[str, Any]):
|
| 22 |
+
"""Mocker for `pydantic_core.CoreSchema` which optionally attempts to
|
| 23 |
+
rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
__slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo'
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
error_message: str,
|
| 31 |
+
*,
|
| 32 |
+
code: PydanticErrorCodes,
|
| 33 |
+
attempt_rebuild: Callable[[], CoreSchema | None] | None = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
self._error_message = error_message
|
| 36 |
+
self._code: PydanticErrorCodes = code
|
| 37 |
+
self._attempt_rebuild = attempt_rebuild
|
| 38 |
+
self._built_memo: CoreSchema | None = None
|
| 39 |
+
|
| 40 |
+
def __getitem__(self, key: str) -> Any:
|
| 41 |
+
return self._get_built().__getitem__(key)
|
| 42 |
+
|
| 43 |
+
def __len__(self) -> int:
|
| 44 |
+
return self._get_built().__len__()
|
| 45 |
+
|
| 46 |
+
def __iter__(self) -> Iterator[str]:
|
| 47 |
+
return self._get_built().__iter__()
|
| 48 |
+
|
| 49 |
+
def _get_built(self) -> CoreSchema:
|
| 50 |
+
if self._built_memo is not None:
|
| 51 |
+
return self._built_memo
|
| 52 |
+
|
| 53 |
+
if self._attempt_rebuild:
|
| 54 |
+
schema = self._attempt_rebuild()
|
| 55 |
+
if schema is not None:
|
| 56 |
+
self._built_memo = schema
|
| 57 |
+
return schema
|
| 58 |
+
raise PydanticUserError(self._error_message, code=self._code)
|
| 59 |
+
|
| 60 |
+
def rebuild(self) -> CoreSchema | None:
|
| 61 |
+
self._built_memo = None
|
| 62 |
+
if self._attempt_rebuild:
|
| 63 |
+
schema = self._attempt_rebuild()
|
| 64 |
+
if schema is not None:
|
| 65 |
+
return schema
|
| 66 |
+
else:
|
| 67 |
+
raise PydanticUserError(self._error_message, code=self._code)
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class MockValSer(Generic[ValSer]):
|
| 72 |
+
"""Mocker for `pydantic_core.SchemaValidator` or `pydantic_core.SchemaSerializer` which optionally attempts to
|
| 73 |
+
rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
__slots__ = '_error_message', '_code', '_val_or_ser', '_attempt_rebuild'
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
error_message: str,
|
| 81 |
+
*,
|
| 82 |
+
code: PydanticErrorCodes,
|
| 83 |
+
val_or_ser: Literal['validator', 'serializer'],
|
| 84 |
+
attempt_rebuild: Callable[[], ValSer | None] | None = None,
|
| 85 |
+
) -> None:
|
| 86 |
+
self._error_message = error_message
|
| 87 |
+
self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer
|
| 88 |
+
self._code: PydanticErrorCodes = code
|
| 89 |
+
self._attempt_rebuild = attempt_rebuild
|
| 90 |
+
|
| 91 |
+
def __getattr__(self, item: str) -> None:
|
| 92 |
+
__tracebackhide__ = True
|
| 93 |
+
if self._attempt_rebuild:
|
| 94 |
+
val_ser = self._attempt_rebuild()
|
| 95 |
+
if val_ser is not None:
|
| 96 |
+
return getattr(val_ser, item)
|
| 97 |
+
|
| 98 |
+
# raise an AttributeError if `item` doesn't exist
|
| 99 |
+
getattr(self._val_or_ser, item)
|
| 100 |
+
raise PydanticUserError(self._error_message, code=self._code)
|
| 101 |
+
|
| 102 |
+
def rebuild(self) -> ValSer | None:
|
| 103 |
+
if self._attempt_rebuild:
|
| 104 |
+
val_ser = self._attempt_rebuild()
|
| 105 |
+
if val_ser is not None:
|
| 106 |
+
return val_ser
|
| 107 |
+
else:
|
| 108 |
+
raise PydanticUserError(self._error_message, code=self._code)
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def set_type_adapter_mocks(adapter: TypeAdapter) -> None:
|
| 113 |
+
"""Set `core_schema`, `validator` and `serializer` to mock core types on a type adapter instance.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
adapter: The type adapter instance to set the mocks on
|
| 117 |
+
"""
|
| 118 |
+
type_repr = str(adapter._type)
|
| 119 |
+
undefined_type_error_message = (
|
| 120 |
+
f'`TypeAdapter[{type_repr}]` is not fully defined; you should define `{type_repr}` and all referenced types,'
|
| 121 |
+
f' then call `.rebuild()` on the instance.'
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> Callable[[], T | None]:
|
| 125 |
+
def handler() -> T | None:
|
| 126 |
+
if adapter.rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:
|
| 127 |
+
return attr_fn(adapter)
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
return handler
|
| 131 |
+
|
| 132 |
+
adapter.core_schema = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
|
| 133 |
+
undefined_type_error_message,
|
| 134 |
+
code='class-not-fully-defined',
|
| 135 |
+
attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.core_schema),
|
| 136 |
+
)
|
| 137 |
+
adapter.validator = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 138 |
+
undefined_type_error_message,
|
| 139 |
+
code='class-not-fully-defined',
|
| 140 |
+
val_or_ser='validator',
|
| 141 |
+
attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.validator),
|
| 142 |
+
)
|
| 143 |
+
adapter.serializer = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 144 |
+
undefined_type_error_message,
|
| 145 |
+
code='class-not-fully-defined',
|
| 146 |
+
val_or_ser='serializer',
|
| 147 |
+
attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.serializer),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def set_model_mocks(cls: type[BaseModel], undefined_name: str = 'all referenced types') -> None:
|
| 152 |
+
"""Set `__pydantic_core_schema__`, `__pydantic_validator__` and `__pydantic_serializer__` to mock core types on a model.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
cls: The model class to set the mocks on
|
| 156 |
+
undefined_name: Name of the undefined thing, used in error messages
|
| 157 |
+
"""
|
| 158 |
+
undefined_type_error_message = (
|
| 159 |
+
f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
|
| 160 |
+
f' then call `{cls.__name__}.model_rebuild()`.'
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> Callable[[], T | None]:
|
| 164 |
+
def handler() -> T | None:
|
| 165 |
+
if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:
|
| 166 |
+
return attr_fn(cls)
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
return handler
|
| 170 |
+
|
| 171 |
+
cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
|
| 172 |
+
undefined_type_error_message,
|
| 173 |
+
code='class-not-fully-defined',
|
| 174 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
|
| 175 |
+
)
|
| 176 |
+
cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 177 |
+
undefined_type_error_message,
|
| 178 |
+
code='class-not-fully-defined',
|
| 179 |
+
val_or_ser='validator',
|
| 180 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
|
| 181 |
+
)
|
| 182 |
+
cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 183 |
+
undefined_type_error_message,
|
| 184 |
+
code='class-not-fully-defined',
|
| 185 |
+
val_or_ser='serializer',
|
| 186 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def set_dataclass_mocks(cls: type[PydanticDataclass], undefined_name: str = 'all referenced types') -> None:
|
| 191 |
+
"""Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a dataclass.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
cls: The model class to set the mocks on
|
| 195 |
+
undefined_name: Name of the undefined thing, used in error messages
|
| 196 |
+
"""
|
| 197 |
+
from ..dataclasses import rebuild_dataclass
|
| 198 |
+
|
| 199 |
+
undefined_type_error_message = (
|
| 200 |
+
f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
|
| 201 |
+
f' then call `pydantic.dataclasses.rebuild_dataclass({cls.__name__})`.'
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> Callable[[], T | None]:
|
| 205 |
+
def handler() -> T | None:
|
| 206 |
+
if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=5) is not False:
|
| 207 |
+
return attr_fn(cls)
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
return handler
|
| 211 |
+
|
| 212 |
+
cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
|
| 213 |
+
undefined_type_error_message,
|
| 214 |
+
code='class-not-fully-defined',
|
| 215 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
|
| 216 |
+
)
|
| 217 |
+
cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 218 |
+
undefined_type_error_message,
|
| 219 |
+
code='class-not-fully-defined',
|
| 220 |
+
val_or_ser='validator',
|
| 221 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
|
| 222 |
+
)
|
| 223 |
+
cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
|
| 224 |
+
undefined_type_error_message,
|
| 225 |
+
code='class-not-fully-defined',
|
| 226 |
+
val_or_ser='serializer',
|
| 227 |
+
attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
|
| 228 |
+
)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_model_construction.py
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 8 |
+
import warnings
|
| 9 |
+
import weakref
|
| 10 |
+
from abc import ABCMeta
|
| 11 |
+
from functools import cache, partial, wraps
|
| 12 |
+
from types import FunctionType
|
| 13 |
+
from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, cast
|
| 14 |
+
|
| 15 |
+
from pydantic_core import PydanticUndefined, SchemaSerializer
|
| 16 |
+
from typing_extensions import TypeAliasType, dataclass_transform, deprecated, get_args, get_origin
|
| 17 |
+
from typing_inspection import typing_objects
|
| 18 |
+
|
| 19 |
+
from ..errors import PydanticUndefinedAnnotation, PydanticUserError
|
| 20 |
+
from ..plugin._schema_validator import create_schema_validator
|
| 21 |
+
from ..warnings import GenericBeforeBaseModelWarning, PydanticDeprecatedSince20
|
| 22 |
+
from ._config import ConfigWrapper
|
| 23 |
+
from ._decorators import DecoratorInfos, PydanticDescriptorProxy, get_attribute_from_bases, unwrap_wrapped_function
|
| 24 |
+
from ._fields import collect_model_fields, is_valid_field_name, is_valid_privateattr_name, rebuild_model_fields
|
| 25 |
+
from ._generate_schema import GenerateSchema, InvalidSchemaError
|
| 26 |
+
from ._generics import PydanticGenericMetadata, get_model_typevars_map
|
| 27 |
+
from ._import_utils import import_cached_base_model, import_cached_field_info
|
| 28 |
+
from ._mock_val_ser import set_model_mocks
|
| 29 |
+
from ._namespace_utils import NsResolver
|
| 30 |
+
from ._signature import generate_pydantic_signature
|
| 31 |
+
from ._typing_extra import (
|
| 32 |
+
_make_forward_ref,
|
| 33 |
+
eval_type_backport,
|
| 34 |
+
is_classvar_annotation,
|
| 35 |
+
parent_frame_namespace,
|
| 36 |
+
)
|
| 37 |
+
from ._utils import LazyClassAttribute, SafeGetItemProxy
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from ..fields import Field as PydanticModelField
|
| 41 |
+
from ..fields import FieldInfo, ModelPrivateAttr
|
| 42 |
+
from ..fields import PrivateAttr as PydanticModelPrivateAttr
|
| 43 |
+
from ..main import BaseModel
|
| 44 |
+
else:
|
| 45 |
+
PydanticModelField = object()
|
| 46 |
+
PydanticModelPrivateAttr = object()
|
| 47 |
+
|
| 48 |
+
object_setattr = object.__setattr__
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _ModelNamespaceDict(dict):
|
| 52 |
+
"""A dictionary subclass that intercepts attribute setting on model classes and
|
| 53 |
+
warns about overriding of decorators.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __setitem__(self, k: str, v: object) -> None:
|
| 57 |
+
existing: Any = self.get(k, None)
|
| 58 |
+
if existing and v is not existing and isinstance(existing, PydanticDescriptorProxy):
|
| 59 |
+
warnings.warn(
|
| 60 |
+
f'`{k}` overrides an existing Pydantic `{existing.decorator_info.decorator_repr}` decorator',
|
| 61 |
+
stacklevel=2,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
return super().__setitem__(k, v)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def NoInitField(
|
| 68 |
+
*,
|
| 69 |
+
init: Literal[False] = False,
|
| 70 |
+
) -> Any:
|
| 71 |
+
"""Only for typing purposes. Used as default value of `__pydantic_fields_set__`,
|
| 72 |
+
`__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when
|
| 73 |
+
synthesizing the `__init__` signature.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# For ModelMetaclass.register():
|
| 78 |
+
_T = TypeVar('_T')
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dataclass_transform(kw_only_default=True, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr, NoInitField))
|
| 82 |
+
class ModelMetaclass(ABCMeta):
|
| 83 |
+
def __new__(
|
| 84 |
+
mcs,
|
| 85 |
+
cls_name: str,
|
| 86 |
+
bases: tuple[type[Any], ...],
|
| 87 |
+
namespace: dict[str, Any],
|
| 88 |
+
__pydantic_generic_metadata__: PydanticGenericMetadata | None = None,
|
| 89 |
+
__pydantic_reset_parent_namespace__: bool = True,
|
| 90 |
+
_create_model_module: str | None = None,
|
| 91 |
+
**kwargs: Any,
|
| 92 |
+
) -> type:
|
| 93 |
+
"""Metaclass for creating Pydantic models.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
cls_name: The name of the class to be created.
|
| 97 |
+
bases: The base classes of the class to be created.
|
| 98 |
+
namespace: The attribute dictionary of the class to be created.
|
| 99 |
+
__pydantic_generic_metadata__: Metadata for generic models.
|
| 100 |
+
__pydantic_reset_parent_namespace__: Reset parent namespace.
|
| 101 |
+
_create_model_module: The module of the class to be created, if created by `create_model`.
|
| 102 |
+
**kwargs: Catch-all for any other keyword arguments.
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
The new class created by the metaclass.
|
| 106 |
+
"""
|
| 107 |
+
# Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we rely on the fact
|
| 108 |
+
# that `BaseModel` itself won't have any bases, but any subclass of it will, to determine whether the `__new__`
|
| 109 |
+
# call we're in the middle of is for the `BaseModel` class.
|
| 110 |
+
if bases:
|
| 111 |
+
raw_annotations: dict[str, Any]
|
| 112 |
+
if sys.version_info >= (3, 14):
|
| 113 |
+
if (
|
| 114 |
+
'__annotations__' in namespace
|
| 115 |
+
): # `from __future__ import annotations` was used in the model's module
|
| 116 |
+
raw_annotations = namespace['__annotations__']
|
| 117 |
+
else:
|
| 118 |
+
# See https://docs.python.org/3.14/library/annotationlib.html#using-annotations-in-a-metaclass:
|
| 119 |
+
from annotationlib import Format, call_annotate_function, get_annotate_from_class_namespace
|
| 120 |
+
|
| 121 |
+
if annotate := get_annotate_from_class_namespace(namespace):
|
| 122 |
+
raw_annotations = call_annotate_function(annotate, format=Format.FORWARDREF)
|
| 123 |
+
else:
|
| 124 |
+
raw_annotations = {}
|
| 125 |
+
else:
|
| 126 |
+
raw_annotations = namespace.get('__annotations__', {})
|
| 127 |
+
|
| 128 |
+
base_field_names, class_vars, base_private_attributes = mcs._collect_bases_data(bases)
|
| 129 |
+
|
| 130 |
+
config_wrapper = ConfigWrapper.for_model(bases, namespace, raw_annotations, kwargs)
|
| 131 |
+
namespace['model_config'] = config_wrapper.config_dict
|
| 132 |
+
private_attributes = inspect_namespace(
|
| 133 |
+
namespace, raw_annotations, config_wrapper.ignored_types, class_vars, base_field_names
|
| 134 |
+
)
|
| 135 |
+
if private_attributes or base_private_attributes:
|
| 136 |
+
original_model_post_init = get_model_post_init(namespace, bases)
|
| 137 |
+
if original_model_post_init is not None:
|
| 138 |
+
# if there are private_attributes and a model_post_init function, we handle both
|
| 139 |
+
|
| 140 |
+
@wraps(original_model_post_init)
|
| 141 |
+
def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None:
|
| 142 |
+
"""We need to both initialize private attributes and call the user-defined model_post_init
|
| 143 |
+
method.
|
| 144 |
+
"""
|
| 145 |
+
init_private_attributes(self, context)
|
| 146 |
+
original_model_post_init(self, context)
|
| 147 |
+
|
| 148 |
+
namespace['model_post_init'] = wrapped_model_post_init
|
| 149 |
+
else:
|
| 150 |
+
namespace['model_post_init'] = init_private_attributes
|
| 151 |
+
|
| 152 |
+
namespace['__class_vars__'] = class_vars
|
| 153 |
+
namespace['__private_attributes__'] = {**base_private_attributes, **private_attributes}
|
| 154 |
+
|
| 155 |
+
cls = cast('type[BaseModel]', super().__new__(mcs, cls_name, bases, namespace, **kwargs))
|
| 156 |
+
BaseModel_ = import_cached_base_model()
|
| 157 |
+
|
| 158 |
+
mro = cls.__mro__
|
| 159 |
+
if Generic in mro and mro.index(Generic) < mro.index(BaseModel_):
|
| 160 |
+
warnings.warn(
|
| 161 |
+
GenericBeforeBaseModelWarning(
|
| 162 |
+
'Classes should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) '
|
| 163 |
+
'for pydantic generics to work properly.'
|
| 164 |
+
),
|
| 165 |
+
stacklevel=2,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
cls.__pydantic_custom_init__ = not getattr(cls.__init__, '__pydantic_base_init__', False)
|
| 169 |
+
cls.__pydantic_post_init__ = (
|
| 170 |
+
None if cls.model_post_init is BaseModel_.model_post_init else 'model_post_init'
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
cls.__pydantic_setattr_handlers__ = {}
|
| 174 |
+
|
| 175 |
+
cls.__pydantic_decorators__ = DecoratorInfos.build(cls)
|
| 176 |
+
cls.__pydantic_decorators__.update_from_config(config_wrapper)
|
| 177 |
+
|
| 178 |
+
# Use the getattr below to grab the __parameters__ from the `typing.Generic` parent class
|
| 179 |
+
if __pydantic_generic_metadata__:
|
| 180 |
+
cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__
|
| 181 |
+
else:
|
| 182 |
+
parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ())
|
| 183 |
+
parameters = getattr(cls, '__parameters__', None) or parent_parameters
|
| 184 |
+
if parameters and parent_parameters and not all(x in parameters for x in parent_parameters):
|
| 185 |
+
from ..root_model import RootModelRootType
|
| 186 |
+
|
| 187 |
+
missing_parameters = tuple(x for x in parameters if x not in parent_parameters)
|
| 188 |
+
if RootModelRootType in parent_parameters and RootModelRootType not in parameters:
|
| 189 |
+
# This is a special case where the user has subclassed `RootModel`, but has not parametrized
|
| 190 |
+
# RootModel with the generic type identifiers being used. Ex:
|
| 191 |
+
# class MyModel(RootModel, Generic[T]):
|
| 192 |
+
# root: T
|
| 193 |
+
# Should instead just be:
|
| 194 |
+
# class MyModel(RootModel[T]):
|
| 195 |
+
# root: T
|
| 196 |
+
parameters_str = ', '.join([x.__name__ for x in missing_parameters])
|
| 197 |
+
error_message = (
|
| 198 |
+
f'{cls.__name__} is a subclass of `RootModel`, but does not include the generic type identifier(s) '
|
| 199 |
+
f'{parameters_str} in its parameters. '
|
| 200 |
+
f'You should parametrize RootModel directly, e.g., `class {cls.__name__}(RootModel[{parameters_str}]): ...`.'
|
| 201 |
+
)
|
| 202 |
+
else:
|
| 203 |
+
combined_parameters = parent_parameters + missing_parameters
|
| 204 |
+
parameters_str = ', '.join([str(x) for x in combined_parameters])
|
| 205 |
+
generic_type_label = f'typing.Generic[{parameters_str}]'
|
| 206 |
+
error_message = (
|
| 207 |
+
f'All parameters must be present on typing.Generic;'
|
| 208 |
+
f' you should inherit from {generic_type_label}.'
|
| 209 |
+
)
|
| 210 |
+
if Generic not in bases: # pragma: no cover
|
| 211 |
+
# We raise an error here not because it is desirable, but because some cases are mishandled.
|
| 212 |
+
# It would be nice to remove this error and still have things behave as expected, it's just
|
| 213 |
+
# challenging because we are using a custom `__class_getitem__` to parametrize generic models,
|
| 214 |
+
# and not returning a typing._GenericAlias from it.
|
| 215 |
+
bases_str = ', '.join([x.__name__ for x in bases] + [generic_type_label])
|
| 216 |
+
error_message += (
|
| 217 |
+
f' Note: `typing.Generic` must go last: `class {cls.__name__}({bases_str}): ...`)'
|
| 218 |
+
)
|
| 219 |
+
raise TypeError(error_message)
|
| 220 |
+
|
| 221 |
+
cls.__pydantic_generic_metadata__ = {
|
| 222 |
+
'origin': None,
|
| 223 |
+
'args': (),
|
| 224 |
+
'parameters': parameters,
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
cls.__pydantic_complete__ = False # Ensure this specific class gets completed
|
| 228 |
+
|
| 229 |
+
# preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
|
| 230 |
+
# for attributes not in `new_namespace` (e.g. private attributes)
|
| 231 |
+
for name, obj in private_attributes.items():
|
| 232 |
+
obj.__set_name__(cls, name)
|
| 233 |
+
|
| 234 |
+
if __pydantic_reset_parent_namespace__:
|
| 235 |
+
cls.__pydantic_parent_namespace__ = build_lenient_weakvaluedict(parent_frame_namespace())
|
| 236 |
+
parent_namespace: dict[str, Any] | None = getattr(cls, '__pydantic_parent_namespace__', None)
|
| 237 |
+
if isinstance(parent_namespace, dict):
|
| 238 |
+
parent_namespace = unpack_lenient_weakvaluedict(parent_namespace)
|
| 239 |
+
|
| 240 |
+
ns_resolver = NsResolver(parent_namespace=parent_namespace)
|
| 241 |
+
|
| 242 |
+
set_model_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
|
| 243 |
+
|
| 244 |
+
# This is also set in `complete_model_class()`, after schema gen because they are recreated.
|
| 245 |
+
# We set them here as well for backwards compatibility:
|
| 246 |
+
cls.__pydantic_computed_fields__ = {
|
| 247 |
+
k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
if config_wrapper.defer_build:
|
| 251 |
+
set_model_mocks(cls)
|
| 252 |
+
else:
|
| 253 |
+
# Any operation that requires accessing the field infos instances should be put inside
|
| 254 |
+
# `complete_model_class()`:
|
| 255 |
+
complete_model_class(
|
| 256 |
+
cls,
|
| 257 |
+
config_wrapper,
|
| 258 |
+
ns_resolver,
|
| 259 |
+
raise_errors=False,
|
| 260 |
+
create_model_module=_create_model_module,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if config_wrapper.frozen and '__hash__' not in namespace:
|
| 264 |
+
set_default_hash_func(cls, bases)
|
| 265 |
+
|
| 266 |
+
# using super(cls, cls) on the next line ensures we only call the parent class's __pydantic_init_subclass__
|
| 267 |
+
# I believe the `type: ignore` is only necessary because mypy doesn't realize that this code branch is
|
| 268 |
+
# only hit for _proper_ subclasses of BaseModel
|
| 269 |
+
super(cls, cls).__pydantic_init_subclass__(**kwargs) # type: ignore[misc]
|
| 270 |
+
return cls
|
| 271 |
+
else:
|
| 272 |
+
# These are instance variables, but have been assigned to `NoInitField` to trick the type checker.
|
| 273 |
+
for instance_slot in '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__':
|
| 274 |
+
namespace.pop(
|
| 275 |
+
instance_slot,
|
| 276 |
+
None, # In case the metaclass is used with a class other than `BaseModel`.
|
| 277 |
+
)
|
| 278 |
+
namespace.get('__annotations__', {}).clear()
|
| 279 |
+
return super().__new__(mcs, cls_name, bases, namespace, **kwargs)
|
| 280 |
+
|
| 281 |
+
if not TYPE_CHECKING: # pragma: no branch
|
| 282 |
+
# We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
|
| 283 |
+
|
| 284 |
+
def __getattr__(self, item: str) -> Any:
|
| 285 |
+
"""This is necessary to keep attribute access working for class attribute access."""
|
| 286 |
+
private_attributes = self.__dict__.get('__private_attributes__')
|
| 287 |
+
if private_attributes and item in private_attributes:
|
| 288 |
+
return private_attributes[item]
|
| 289 |
+
raise AttributeError(item)
|
| 290 |
+
|
| 291 |
+
@classmethod
|
| 292 |
+
def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]:
|
| 293 |
+
return _ModelNamespaceDict()
|
| 294 |
+
|
| 295 |
+
# Due to performance and memory issues, in the ABCMeta.__subclasscheck__ implementation, we don't support
|
| 296 |
+
# registered virtual subclasses. See https://github.com/python/cpython/issues/92810#issuecomment-2762454345.
|
| 297 |
+
# This may change once the CPython gets fixed (possibly in 3.15), in which case we should conditionally
|
| 298 |
+
# define `register()`.
|
| 299 |
+
def register(self, subclass: type[_T]) -> type[_T]:
|
| 300 |
+
warnings.warn(
|
| 301 |
+
f"For performance reasons, virtual subclasses registered using '{self.__qualname__}.register()' "
|
| 302 |
+
"are not supported in 'isinstance()' and 'issubclass()' checks.",
|
| 303 |
+
stacklevel=2,
|
| 304 |
+
)
|
| 305 |
+
return super().register(subclass)
|
| 306 |
+
|
| 307 |
+
__instancecheck__ = type.__instancecheck__ # pyright: ignore[reportAssignmentType]
|
| 308 |
+
__subclasscheck__ = type.__subclasscheck__ # pyright: ignore[reportAssignmentType]
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]:
|
| 312 |
+
BaseModel = import_cached_base_model()
|
| 313 |
+
|
| 314 |
+
field_names: set[str] = set()
|
| 315 |
+
class_vars: set[str] = set()
|
| 316 |
+
private_attributes: dict[str, ModelPrivateAttr] = {}
|
| 317 |
+
for base in bases:
|
| 318 |
+
if issubclass(base, BaseModel) and base is not BaseModel:
|
| 319 |
+
# model_fields might not be defined yet in the case of generics, so we use getattr here:
|
| 320 |
+
field_names.update(getattr(base, '__pydantic_fields__', {}).keys())
|
| 321 |
+
class_vars.update(base.__class_vars__)
|
| 322 |
+
private_attributes.update(base.__private_attributes__)
|
| 323 |
+
return field_names, class_vars, private_attributes
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
@deprecated(
|
| 327 |
+
'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', category=None
|
| 328 |
+
)
|
| 329 |
+
def __fields__(self) -> dict[str, FieldInfo]:
|
| 330 |
+
warnings.warn(
|
| 331 |
+
'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.',
|
| 332 |
+
PydanticDeprecatedSince20,
|
| 333 |
+
stacklevel=2,
|
| 334 |
+
)
|
| 335 |
+
return getattr(self, '__pydantic_fields__', {})
|
| 336 |
+
|
| 337 |
+
@property
|
| 338 |
+
def __pydantic_fields_complete__(self) -> bool:
|
| 339 |
+
"""Whether the fields where successfully collected (i.e. type hints were successfully resolves).
|
| 340 |
+
|
| 341 |
+
This is a private attribute, not meant to be used outside Pydantic.
|
| 342 |
+
"""
|
| 343 |
+
if '__pydantic_fields__' not in self.__dict__:
|
| 344 |
+
return False
|
| 345 |
+
|
| 346 |
+
field_infos = cast('dict[str, FieldInfo]', self.__pydantic_fields__) # pyright: ignore[reportAttributeAccessIssue]
|
| 347 |
+
|
| 348 |
+
return all(field_info._complete for field_info in field_infos.values())
|
| 349 |
+
|
| 350 |
+
def __dir__(self) -> list[str]:
|
| 351 |
+
attributes = list(super().__dir__())
|
| 352 |
+
if '__fields__' in attributes:
|
| 353 |
+
attributes.remove('__fields__')
|
| 354 |
+
return attributes
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def init_private_attributes(self: BaseModel, context: Any, /) -> None:
|
| 358 |
+
"""This function is meant to behave like a BaseModel method to initialise private attributes.
|
| 359 |
+
|
| 360 |
+
It takes context as an argument since that's what pydantic-core passes when calling it.
|
| 361 |
+
|
| 362 |
+
Args:
|
| 363 |
+
self: The BaseModel instance.
|
| 364 |
+
context: The context.
|
| 365 |
+
"""
|
| 366 |
+
if getattr(self, '__pydantic_private__', None) is None:
|
| 367 |
+
pydantic_private = {}
|
| 368 |
+
for name, private_attr in self.__private_attributes__.items():
|
| 369 |
+
default = private_attr.get_default()
|
| 370 |
+
if default is not PydanticUndefined:
|
| 371 |
+
pydantic_private[name] = default
|
| 372 |
+
object_setattr(self, '__pydantic_private__', pydantic_private)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def get_model_post_init(namespace: dict[str, Any], bases: tuple[type[Any], ...]) -> Callable[..., Any] | None:
|
| 376 |
+
"""Get the `model_post_init` method from the namespace or the class bases, or `None` if not defined."""
|
| 377 |
+
if 'model_post_init' in namespace:
|
| 378 |
+
return namespace['model_post_init']
|
| 379 |
+
|
| 380 |
+
BaseModel = import_cached_base_model()
|
| 381 |
+
|
| 382 |
+
model_post_init = get_attribute_from_bases(bases, 'model_post_init')
|
| 383 |
+
if model_post_init is not BaseModel.model_post_init:
|
| 384 |
+
return model_post_init
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def inspect_namespace( # noqa C901
|
| 388 |
+
namespace: dict[str, Any],
|
| 389 |
+
raw_annotations: dict[str, Any],
|
| 390 |
+
ignored_types: tuple[type[Any], ...],
|
| 391 |
+
base_class_vars: set[str],
|
| 392 |
+
base_class_fields: set[str],
|
| 393 |
+
) -> dict[str, ModelPrivateAttr]:
|
| 394 |
+
"""Iterate over the namespace and:
|
| 395 |
+
* gather private attributes
|
| 396 |
+
* check for items which look like fields but are not (e.g. have no annotation) and warn.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
namespace: The attribute dictionary of the class to be created.
|
| 400 |
+
raw_annotations: The (non-evaluated) annotations of the model.
|
| 401 |
+
ignored_types: A tuple of ignore types.
|
| 402 |
+
base_class_vars: A set of base class class variables.
|
| 403 |
+
base_class_fields: A set of base class fields.
|
| 404 |
+
|
| 405 |
+
Returns:
|
| 406 |
+
A dict contains private attributes info.
|
| 407 |
+
|
| 408 |
+
Raises:
|
| 409 |
+
TypeError: If there is a `__root__` field in model.
|
| 410 |
+
NameError: If private attribute name is invalid.
|
| 411 |
+
PydanticUserError:
|
| 412 |
+
- If a field does not have a type annotation.
|
| 413 |
+
- If a field on base class was overridden by a non-annotated attribute.
|
| 414 |
+
"""
|
| 415 |
+
from ..fields import ModelPrivateAttr, PrivateAttr
|
| 416 |
+
|
| 417 |
+
FieldInfo = import_cached_field_info()
|
| 418 |
+
|
| 419 |
+
all_ignored_types = ignored_types + default_ignored_types()
|
| 420 |
+
|
| 421 |
+
private_attributes: dict[str, ModelPrivateAttr] = {}
|
| 422 |
+
|
| 423 |
+
if '__root__' in raw_annotations or '__root__' in namespace:
|
| 424 |
+
raise TypeError("To define root models, use `pydantic.RootModel` rather than a field called '__root__'")
|
| 425 |
+
|
| 426 |
+
ignored_names: set[str] = set()
|
| 427 |
+
for var_name, value in list(namespace.items()):
|
| 428 |
+
if var_name == 'model_config' or var_name == '__pydantic_extra__':
|
| 429 |
+
continue
|
| 430 |
+
elif (
|
| 431 |
+
isinstance(value, type)
|
| 432 |
+
and value.__module__ == namespace['__module__']
|
| 433 |
+
and '__qualname__' in namespace
|
| 434 |
+
and value.__qualname__.startswith(f'{namespace["__qualname__"]}.')
|
| 435 |
+
):
|
| 436 |
+
# `value` is a nested type defined in this namespace; don't error
|
| 437 |
+
continue
|
| 438 |
+
elif isinstance(value, all_ignored_types) or value.__class__.__module__ == 'functools':
|
| 439 |
+
ignored_names.add(var_name)
|
| 440 |
+
continue
|
| 441 |
+
elif isinstance(value, ModelPrivateAttr):
|
| 442 |
+
if var_name.startswith('__'):
|
| 443 |
+
raise NameError(
|
| 444 |
+
'Private attributes must not use dunder names;'
|
| 445 |
+
f' use a single underscore prefix instead of {var_name!r}.'
|
| 446 |
+
)
|
| 447 |
+
elif is_valid_field_name(var_name):
|
| 448 |
+
raise NameError(
|
| 449 |
+
'Private attributes must not use valid field names;'
|
| 450 |
+
f' use sunder names, e.g. {"_" + var_name!r} instead of {var_name!r}.'
|
| 451 |
+
)
|
| 452 |
+
private_attributes[var_name] = value
|
| 453 |
+
del namespace[var_name]
|
| 454 |
+
elif isinstance(value, FieldInfo) and not is_valid_field_name(var_name):
|
| 455 |
+
suggested_name = var_name.lstrip('_') or 'my_field' # don't suggest '' for all-underscore name
|
| 456 |
+
raise NameError(
|
| 457 |
+
f'Fields must not use names with leading underscores;'
|
| 458 |
+
f' e.g., use {suggested_name!r} instead of {var_name!r}.'
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
elif var_name.startswith('__'):
|
| 462 |
+
continue
|
| 463 |
+
elif is_valid_privateattr_name(var_name):
|
| 464 |
+
if var_name not in raw_annotations or not is_classvar_annotation(raw_annotations[var_name]):
|
| 465 |
+
private_attributes[var_name] = cast(ModelPrivateAttr, PrivateAttr(default=value))
|
| 466 |
+
del namespace[var_name]
|
| 467 |
+
elif var_name in base_class_vars:
|
| 468 |
+
continue
|
| 469 |
+
elif var_name not in raw_annotations:
|
| 470 |
+
if var_name in base_class_fields:
|
| 471 |
+
raise PydanticUserError(
|
| 472 |
+
f'Field {var_name!r} defined on a base class was overridden by a non-annotated attribute. '
|
| 473 |
+
f'All field definitions, including overrides, require a type annotation.',
|
| 474 |
+
code='model-field-overridden',
|
| 475 |
+
)
|
| 476 |
+
elif isinstance(value, FieldInfo):
|
| 477 |
+
raise PydanticUserError(
|
| 478 |
+
f'Field {var_name!r} requires a type annotation', code='model-field-missing-annotation'
|
| 479 |
+
)
|
| 480 |
+
else:
|
| 481 |
+
raise PydanticUserError(
|
| 482 |
+
f'A non-annotated attribute was detected: `{var_name} = {value!r}`. All model fields require a '
|
| 483 |
+
f'type annotation; if `{var_name}` is not meant to be a field, you may be able to resolve this '
|
| 484 |
+
f"error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.",
|
| 485 |
+
code='model-field-missing-annotation',
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
for ann_name, ann_type in raw_annotations.items():
|
| 489 |
+
if (
|
| 490 |
+
is_valid_privateattr_name(ann_name)
|
| 491 |
+
and ann_name not in private_attributes
|
| 492 |
+
and ann_name not in ignored_names
|
| 493 |
+
# This condition can be a false negative when `ann_type` is stringified,
|
| 494 |
+
# but it is handled in most cases in `set_model_fields`:
|
| 495 |
+
and not is_classvar_annotation(ann_type)
|
| 496 |
+
and ann_type not in all_ignored_types
|
| 497 |
+
and getattr(ann_type, '__module__', None) != 'functools'
|
| 498 |
+
):
|
| 499 |
+
if isinstance(ann_type, str):
|
| 500 |
+
# Walking up the frames to get the module namespace where the model is defined
|
| 501 |
+
# (as the model class wasn't created yet, we unfortunately can't use `cls.__module__`):
|
| 502 |
+
frame = sys._getframe(2)
|
| 503 |
+
if frame is not None:
|
| 504 |
+
try:
|
| 505 |
+
ann_type = eval_type_backport(
|
| 506 |
+
_make_forward_ref(ann_type, is_argument=False, is_class=True),
|
| 507 |
+
globalns=frame.f_globals,
|
| 508 |
+
localns=frame.f_locals,
|
| 509 |
+
)
|
| 510 |
+
except (NameError, TypeError):
|
| 511 |
+
pass
|
| 512 |
+
|
| 513 |
+
if typing_objects.is_annotated(get_origin(ann_type)):
|
| 514 |
+
_, *metadata = get_args(ann_type)
|
| 515 |
+
private_attr = next((v for v in metadata if isinstance(v, ModelPrivateAttr)), None)
|
| 516 |
+
if private_attr is not None:
|
| 517 |
+
private_attributes[ann_name] = private_attr
|
| 518 |
+
continue
|
| 519 |
+
private_attributes[ann_name] = PrivateAttr()
|
| 520 |
+
|
| 521 |
+
return private_attributes
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def set_default_hash_func(cls: type[BaseModel], bases: tuple[type[Any], ...]) -> None:
|
| 525 |
+
base_hash_func = get_attribute_from_bases(bases, '__hash__')
|
| 526 |
+
new_hash_func = make_hash_func(cls)
|
| 527 |
+
if base_hash_func in {None, object.__hash__} or getattr(base_hash_func, '__code__', None) == new_hash_func.__code__:
|
| 528 |
+
# If `__hash__` is some default, we generate a hash function.
|
| 529 |
+
# It will be `None` if not overridden from BaseModel.
|
| 530 |
+
# It may be `object.__hash__` if there is another
|
| 531 |
+
# parent class earlier in the bases which doesn't override `__hash__` (e.g. `typing.Generic`).
|
| 532 |
+
# It may be a value set by `set_default_hash_func` if `cls` is a subclass of another frozen model.
|
| 533 |
+
# In the last case we still need a new hash function to account for new `model_fields`.
|
| 534 |
+
cls.__hash__ = new_hash_func
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def make_hash_func(cls: type[BaseModel]) -> Any:
|
| 538 |
+
getter = operator.itemgetter(*cls.__pydantic_fields__.keys()) if cls.__pydantic_fields__ else lambda _: 0
|
| 539 |
+
|
| 540 |
+
def hash_func(self: Any) -> int:
|
| 541 |
+
try:
|
| 542 |
+
return hash(getter(self.__dict__))
|
| 543 |
+
except KeyError:
|
| 544 |
+
# In rare cases (such as when using the deprecated copy method), the __dict__ may not contain
|
| 545 |
+
# all model fields, which is how we can get here.
|
| 546 |
+
# getter(self.__dict__) is much faster than any 'safe' method that accounts for missing keys,
|
| 547 |
+
# and wrapping it in a `try` doesn't slow things down much in the common case.
|
| 548 |
+
return hash(getter(SafeGetItemProxy(self.__dict__)))
|
| 549 |
+
|
| 550 |
+
return hash_func
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def set_model_fields(
|
| 554 |
+
cls: type[BaseModel],
|
| 555 |
+
config_wrapper: ConfigWrapper,
|
| 556 |
+
ns_resolver: NsResolver | None,
|
| 557 |
+
) -> None:
|
| 558 |
+
"""Collect and set `cls.__pydantic_fields__` and `cls.__class_vars__`.
|
| 559 |
+
|
| 560 |
+
Args:
|
| 561 |
+
cls: BaseModel or dataclass.
|
| 562 |
+
config_wrapper: The config wrapper instance.
|
| 563 |
+
ns_resolver: Namespace resolver to use when getting model annotations.
|
| 564 |
+
"""
|
| 565 |
+
typevars_map = get_model_typevars_map(cls)
|
| 566 |
+
fields, class_vars = collect_model_fields(cls, config_wrapper, ns_resolver, typevars_map=typevars_map)
|
| 567 |
+
|
| 568 |
+
cls.__pydantic_fields__ = fields
|
| 569 |
+
cls.__class_vars__.update(class_vars)
|
| 570 |
+
|
| 571 |
+
for k in class_vars:
|
| 572 |
+
# Class vars should not be private attributes
|
| 573 |
+
# We remove them _here_ and not earlier because we rely on inspecting the class to determine its classvars,
|
| 574 |
+
# but private attributes are determined by inspecting the namespace _prior_ to class creation.
|
| 575 |
+
# In the case that a classvar with a leading-'_' is defined via a ForwardRef (e.g., when using
|
| 576 |
+
# `__future__.annotations`), we want to remove the private attribute which was detected _before_ we knew it
|
| 577 |
+
# evaluated to a classvar
|
| 578 |
+
|
| 579 |
+
value = cls.__private_attributes__.pop(k, None)
|
| 580 |
+
if value is not None and value.default is not PydanticUndefined:
|
| 581 |
+
setattr(cls, k, value.default)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def complete_model_class(
|
| 585 |
+
cls: type[BaseModel],
|
| 586 |
+
config_wrapper: ConfigWrapper,
|
| 587 |
+
ns_resolver: NsResolver,
|
| 588 |
+
*,
|
| 589 |
+
raise_errors: bool = True,
|
| 590 |
+
call_on_complete_hook: bool = True,
|
| 591 |
+
create_model_module: str | None = None,
|
| 592 |
+
) -> bool:
|
| 593 |
+
"""Finish building a model class.
|
| 594 |
+
|
| 595 |
+
This logic must be called after class has been created since validation functions must be bound
|
| 596 |
+
and `get_type_hints` requires a class object.
|
| 597 |
+
|
| 598 |
+
Args:
|
| 599 |
+
cls: BaseModel or dataclass.
|
| 600 |
+
config_wrapper: The config wrapper instance.
|
| 601 |
+
ns_resolver: The namespace resolver instance to use during schema building.
|
| 602 |
+
raise_errors: Whether to raise errors.
|
| 603 |
+
call_on_complete_hook: Whether to call the `__pydantic_on_complete__` hook.
|
| 604 |
+
create_model_module: The module of the class to be created, if created by `create_model`.
|
| 605 |
+
|
| 606 |
+
Returns:
|
| 607 |
+
`True` if the model is successfully completed, else `False`.
|
| 608 |
+
|
| 609 |
+
Raises:
|
| 610 |
+
PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
|
| 611 |
+
and `raise_errors=True`.
|
| 612 |
+
"""
|
| 613 |
+
typevars_map = get_model_typevars_map(cls)
|
| 614 |
+
|
| 615 |
+
if not cls.__pydantic_fields_complete__:
|
| 616 |
+
# Note: when coming from `ModelMetaclass.__new__()`, this results in fields being built twice.
|
| 617 |
+
# We do so a second time here so that we can get the `NameError` for the specific undefined annotation.
|
| 618 |
+
# Alternatively, we could let `GenerateSchema()` raise the error, but there are cases where incomplete
|
| 619 |
+
# fields are inherited in `collect_model_fields()` and can actually have their annotation resolved in the
|
| 620 |
+
# generate schema process. As we want to avoid having `__pydantic_fields_complete__` set to `False`
|
| 621 |
+
# when `__pydantic_complete__` is `True`, we rebuild here:
|
| 622 |
+
try:
|
| 623 |
+
cls.__pydantic_fields__ = rebuild_model_fields(
|
| 624 |
+
cls,
|
| 625 |
+
config_wrapper=config_wrapper,
|
| 626 |
+
ns_resolver=ns_resolver,
|
| 627 |
+
typevars_map=typevars_map,
|
| 628 |
+
)
|
| 629 |
+
except NameError as e:
|
| 630 |
+
exc = PydanticUndefinedAnnotation.from_name_error(e)
|
| 631 |
+
set_model_mocks(cls, f'`{exc.name}`')
|
| 632 |
+
if raise_errors:
|
| 633 |
+
raise exc from e
|
| 634 |
+
|
| 635 |
+
if not raise_errors and not cls.__pydantic_fields_complete__:
|
| 636 |
+
# No need to continue with schema gen, it is guaranteed to fail
|
| 637 |
+
return False
|
| 638 |
+
|
| 639 |
+
assert cls.__pydantic_fields_complete__
|
| 640 |
+
|
| 641 |
+
gen_schema = GenerateSchema(
|
| 642 |
+
config_wrapper,
|
| 643 |
+
ns_resolver,
|
| 644 |
+
typevars_map,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
try:
|
| 648 |
+
schema = gen_schema.generate_schema(cls)
|
| 649 |
+
except PydanticUndefinedAnnotation as e:
|
| 650 |
+
if raise_errors:
|
| 651 |
+
raise
|
| 652 |
+
set_model_mocks(cls, f'`{e.name}`')
|
| 653 |
+
return False
|
| 654 |
+
|
| 655 |
+
core_config = config_wrapper.core_config(title=cls.__name__)
|
| 656 |
+
|
| 657 |
+
try:
|
| 658 |
+
schema = gen_schema.clean_schema(schema)
|
| 659 |
+
except InvalidSchemaError:
|
| 660 |
+
set_model_mocks(cls)
|
| 661 |
+
return False
|
| 662 |
+
|
| 663 |
+
# This needs to happen *after* model schema generation, as the return type
|
| 664 |
+
# of the properties are evaluated and the `ComputedFieldInfo` are recreated:
|
| 665 |
+
cls.__pydantic_computed_fields__ = {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()}
|
| 666 |
+
|
| 667 |
+
set_deprecated_descriptors(cls)
|
| 668 |
+
|
| 669 |
+
cls.__pydantic_core_schema__ = schema
|
| 670 |
+
|
| 671 |
+
cls.__pydantic_validator__ = create_schema_validator(
|
| 672 |
+
schema,
|
| 673 |
+
cls,
|
| 674 |
+
create_model_module or cls.__module__,
|
| 675 |
+
cls.__qualname__,
|
| 676 |
+
'create_model' if create_model_module else 'BaseModel',
|
| 677 |
+
core_config,
|
| 678 |
+
config_wrapper.plugin_settings,
|
| 679 |
+
)
|
| 680 |
+
cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config)
|
| 681 |
+
|
| 682 |
+
# set __signature__ attr only for model class, but not for its instances
|
| 683 |
+
# (because instances can define `__call__`, and `inspect.signature` shouldn't
|
| 684 |
+
# use the `__signature__` attribute and instead generate from `__call__`).
|
| 685 |
+
cls.__signature__ = LazyClassAttribute(
|
| 686 |
+
'__signature__',
|
| 687 |
+
partial(
|
| 688 |
+
generate_pydantic_signature,
|
| 689 |
+
init=cls.__init__,
|
| 690 |
+
fields=cls.__pydantic_fields__,
|
| 691 |
+
validate_by_name=config_wrapper.validate_by_name,
|
| 692 |
+
extra=config_wrapper.extra,
|
| 693 |
+
),
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
cls.__pydantic_complete__ = True
|
| 697 |
+
|
| 698 |
+
if call_on_complete_hook:
|
| 699 |
+
cls.__pydantic_on_complete__()
|
| 700 |
+
|
| 701 |
+
return True
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def set_deprecated_descriptors(cls: type[BaseModel]) -> None:
|
| 705 |
+
"""Set data descriptors on the class for deprecated fields."""
|
| 706 |
+
for field, field_info in cls.__pydantic_fields__.items():
|
| 707 |
+
if (msg := field_info.deprecation_message) is not None:
|
| 708 |
+
desc = _DeprecatedFieldDescriptor(msg)
|
| 709 |
+
desc.__set_name__(cls, field)
|
| 710 |
+
setattr(cls, field, desc)
|
| 711 |
+
|
| 712 |
+
for field, computed_field_info in cls.__pydantic_computed_fields__.items():
|
| 713 |
+
if (
|
| 714 |
+
(msg := computed_field_info.deprecation_message) is not None
|
| 715 |
+
# Avoid having two warnings emitted:
|
| 716 |
+
and not hasattr(unwrap_wrapped_function(computed_field_info.wrapped_property), '__deprecated__')
|
| 717 |
+
):
|
| 718 |
+
desc = _DeprecatedFieldDescriptor(msg, computed_field_info.wrapped_property)
|
| 719 |
+
desc.__set_name__(cls, field)
|
| 720 |
+
setattr(cls, field, desc)
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
class _DeprecatedFieldDescriptor:
|
| 724 |
+
"""Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
|
| 725 |
+
|
| 726 |
+
Attributes:
|
| 727 |
+
msg: The deprecation message to be emitted.
|
| 728 |
+
wrapped_property: The property instance if the deprecated field is a computed field, or `None`.
|
| 729 |
+
field_name: The name of the field being deprecated.
|
| 730 |
+
"""
|
| 731 |
+
|
| 732 |
+
field_name: str
|
| 733 |
+
|
| 734 |
+
def __init__(self, msg: str, wrapped_property: property | None = None) -> None:
|
| 735 |
+
self.msg = msg
|
| 736 |
+
self.wrapped_property = wrapped_property
|
| 737 |
+
|
| 738 |
+
def __set_name__(self, cls: type[BaseModel], name: str) -> None:
|
| 739 |
+
self.field_name = name
|
| 740 |
+
|
| 741 |
+
def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any:
|
| 742 |
+
if obj is None:
|
| 743 |
+
if self.wrapped_property is not None:
|
| 744 |
+
return self.wrapped_property.__get__(None, obj_type)
|
| 745 |
+
raise AttributeError(self.field_name)
|
| 746 |
+
|
| 747 |
+
warnings.warn(self.msg, DeprecationWarning, stacklevel=2)
|
| 748 |
+
|
| 749 |
+
if self.wrapped_property is not None:
|
| 750 |
+
return self.wrapped_property.__get__(obj, obj_type)
|
| 751 |
+
return obj.__dict__[self.field_name]
|
| 752 |
+
|
| 753 |
+
# Defined to make it a data descriptor and take precedence over the instance's dictionary.
|
| 754 |
+
# Note that it will not be called when setting a value on a model instance
|
| 755 |
+
# as `BaseModel.__setattr__` is defined and takes priority.
|
| 756 |
+
def __set__(self, obj: Any, value: Any) -> NoReturn:
|
| 757 |
+
raise AttributeError(self.field_name)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
class _PydanticWeakRef:
|
| 761 |
+
"""Wrapper for `weakref.ref` that enables `pickle` serialization.
|
| 762 |
+
|
| 763 |
+
Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related
|
| 764 |
+
to abstract base classes (`abc.ABC`). This class works around the issue by wrapping
|
| 765 |
+
`weakref.ref` instead of subclassing it.
|
| 766 |
+
|
| 767 |
+
See https://github.com/pydantic/pydantic/issues/6763 for context.
|
| 768 |
+
|
| 769 |
+
Semantics:
|
| 770 |
+
- If not pickled, behaves the same as a `weakref.ref`.
|
| 771 |
+
- If pickled along with the referenced object, the same `weakref.ref` behavior
|
| 772 |
+
will be maintained between them after unpickling.
|
| 773 |
+
- If pickled without the referenced object, after unpickling the underlying
|
| 774 |
+
reference will be cleared (`__call__` will always return `None`).
|
| 775 |
+
"""
|
| 776 |
+
|
| 777 |
+
def __init__(self, obj: Any):
|
| 778 |
+
if obj is None:
|
| 779 |
+
# The object will be `None` upon deserialization if the serialized weakref
|
| 780 |
+
# had lost its underlying object.
|
| 781 |
+
self._wr = None
|
| 782 |
+
else:
|
| 783 |
+
self._wr = weakref.ref(obj)
|
| 784 |
+
|
| 785 |
+
def __call__(self) -> Any:
|
| 786 |
+
if self._wr is None:
|
| 787 |
+
return None
|
| 788 |
+
else:
|
| 789 |
+
return self._wr()
|
| 790 |
+
|
| 791 |
+
def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]:
|
| 792 |
+
return _PydanticWeakRef, (self(),)
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def build_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
|
| 796 |
+
"""Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs.
|
| 797 |
+
|
| 798 |
+
We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values
|
| 799 |
+
in a WeakValueDictionary.
|
| 800 |
+
|
| 801 |
+
The `unpack_lenient_weakvaluedict` function can be used to reverse this operation.
|
| 802 |
+
"""
|
| 803 |
+
if d is None:
|
| 804 |
+
return None
|
| 805 |
+
result = {}
|
| 806 |
+
for k, v in d.items():
|
| 807 |
+
try:
|
| 808 |
+
proxy = _PydanticWeakRef(v)
|
| 809 |
+
except TypeError:
|
| 810 |
+
proxy = v
|
| 811 |
+
result[k] = proxy
|
| 812 |
+
return result
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
|
| 816 |
+
"""Inverts the transform performed by `build_lenient_weakvaluedict`."""
|
| 817 |
+
if d is None:
|
| 818 |
+
return None
|
| 819 |
+
|
| 820 |
+
result = {}
|
| 821 |
+
for k, v in d.items():
|
| 822 |
+
if isinstance(v, _PydanticWeakRef):
|
| 823 |
+
v = v()
|
| 824 |
+
if v is not None:
|
| 825 |
+
result[k] = v
|
| 826 |
+
else:
|
| 827 |
+
result[k] = v
|
| 828 |
+
return result
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@cache
|
| 832 |
+
def default_ignored_types() -> tuple[type[Any], ...]:
|
| 833 |
+
from ..fields import ComputedFieldInfo
|
| 834 |
+
|
| 835 |
+
ignored_types = [
|
| 836 |
+
FunctionType,
|
| 837 |
+
property,
|
| 838 |
+
classmethod,
|
| 839 |
+
staticmethod,
|
| 840 |
+
PydanticDescriptorProxy,
|
| 841 |
+
ComputedFieldInfo,
|
| 842 |
+
TypeAliasType, # from `typing_extensions`
|
| 843 |
+
]
|
| 844 |
+
|
| 845 |
+
if sys.version_info >= (3, 12):
|
| 846 |
+
ignored_types.append(typing.TypeAliasType)
|
| 847 |
+
|
| 848 |
+
return tuple(ignored_types)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_namespace_utils.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Generator, Iterator, Mapping
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from functools import cached_property
|
| 7 |
+
from typing import Any, Callable, NamedTuple, TypeVar
|
| 8 |
+
|
| 9 |
+
from typing_extensions import ParamSpec, TypeAlias, TypeAliasType, TypeVarTuple
|
| 10 |
+
|
| 11 |
+
GlobalsNamespace: TypeAlias = 'dict[str, Any]'
|
| 12 |
+
"""A global namespace.
|
| 13 |
+
|
| 14 |
+
In most cases, this is a reference to the `__dict__` attribute of a module.
|
| 15 |
+
This namespace type is expected as the `globals` argument during annotations evaluation.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
MappingNamespace: TypeAlias = Mapping[str, Any]
|
| 19 |
+
"""Any kind of namespace.
|
| 20 |
+
|
| 21 |
+
In most cases, this is a local namespace (e.g. the `__dict__` attribute of a class,
|
| 22 |
+
the [`f_locals`][frame.f_locals] attribute of a frame object, when dealing with types
|
| 23 |
+
defined inside functions).
|
| 24 |
+
This namespace type is expected as the `locals` argument during annotations evaluation.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
_TypeVarLike: TypeAlias = 'TypeVar | ParamSpec | TypeVarTuple'
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class NamespacesTuple(NamedTuple):
|
| 31 |
+
"""A tuple of globals and locals to be used during annotations evaluation.
|
| 32 |
+
|
| 33 |
+
This datastructure is defined as a named tuple so that it can easily be unpacked:
|
| 34 |
+
|
| 35 |
+
```python {lint="skip" test="skip"}
|
| 36 |
+
def eval_type(typ: type[Any], ns: NamespacesTuple) -> None:
|
| 37 |
+
return eval(typ, *ns)
|
| 38 |
+
```
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
globals: GlobalsNamespace
|
| 42 |
+
"""The namespace to be used as the `globals` argument during annotations evaluation."""
|
| 43 |
+
|
| 44 |
+
locals: MappingNamespace
|
| 45 |
+
"""The namespace to be used as the `locals` argument during annotations evaluation."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_module_ns_of(obj: Any) -> dict[str, Any]:
|
| 49 |
+
"""Get the namespace of the module where the object is defined.
|
| 50 |
+
|
| 51 |
+
Caution: this function does not return a copy of the module namespace, so the result
|
| 52 |
+
should not be mutated. The burden of enforcing this is on the caller.
|
| 53 |
+
"""
|
| 54 |
+
module_name = getattr(obj, '__module__', None)
|
| 55 |
+
if module_name:
|
| 56 |
+
try:
|
| 57 |
+
return sys.modules[module_name].__dict__
|
| 58 |
+
except KeyError:
|
| 59 |
+
# happens occasionally, see https://github.com/pydantic/pydantic/issues/2363
|
| 60 |
+
return {}
|
| 61 |
+
return {}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Note that this class is almost identical to `collections.ChainMap`, but need to enforce
|
| 65 |
+
# immutable mappings here:
|
| 66 |
+
class LazyLocalNamespace(Mapping[str, Any]):
|
| 67 |
+
"""A lazily evaluated mapping, to be used as the `locals` argument during annotations evaluation.
|
| 68 |
+
|
| 69 |
+
While the [`eval`][eval] function expects a mapping as the `locals` argument, it only
|
| 70 |
+
performs `__getitem__` calls. The [`Mapping`][collections.abc.Mapping] abstract base class
|
| 71 |
+
is fully implemented only for type checking purposes.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
*namespaces: The namespaces to consider, in ascending order of priority.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
```python {lint="skip" test="skip"}
|
| 78 |
+
ns = LazyLocalNamespace({'a': 1, 'b': 2}, {'a': 3})
|
| 79 |
+
ns['a']
|
| 80 |
+
#> 3
|
| 81 |
+
ns['b']
|
| 82 |
+
#> 2
|
| 83 |
+
```
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, *namespaces: MappingNamespace) -> None:
|
| 87 |
+
self._namespaces = namespaces
|
| 88 |
+
|
| 89 |
+
@cached_property
|
| 90 |
+
def data(self) -> dict[str, Any]:
|
| 91 |
+
return {k: v for ns in self._namespaces for k, v in ns.items()}
|
| 92 |
+
|
| 93 |
+
def __len__(self) -> int:
|
| 94 |
+
return len(self.data)
|
| 95 |
+
|
| 96 |
+
def __getitem__(self, key: str) -> Any:
|
| 97 |
+
return self.data[key]
|
| 98 |
+
|
| 99 |
+
def __contains__(self, key: object) -> bool:
|
| 100 |
+
return key in self.data
|
| 101 |
+
|
| 102 |
+
def __iter__(self) -> Iterator[str]:
|
| 103 |
+
return iter(self.data)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def ns_for_function(obj: Callable[..., Any], parent_namespace: MappingNamespace | None = None) -> NamespacesTuple:
|
| 107 |
+
"""Return the global and local namespaces to be used when evaluating annotations for the provided function.
|
| 108 |
+
|
| 109 |
+
The global namespace will be the `__dict__` attribute of the module the function was defined in.
|
| 110 |
+
The local namespace will contain the `__type_params__` introduced by PEP 695.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
obj: The object to use when building namespaces.
|
| 114 |
+
parent_namespace: Optional namespace to be added with the lowest priority in the local namespace.
|
| 115 |
+
If the passed function is a method, the `parent_namespace` will be the namespace of the class
|
| 116 |
+
the method is defined in. Thus, we also fetch type `__type_params__` from there (i.e. the
|
| 117 |
+
class-scoped type variables).
|
| 118 |
+
"""
|
| 119 |
+
locals_list: list[MappingNamespace] = []
|
| 120 |
+
if parent_namespace is not None:
|
| 121 |
+
locals_list.append(parent_namespace)
|
| 122 |
+
|
| 123 |
+
# Get the `__type_params__` attribute introduced by PEP 695.
|
| 124 |
+
# Note that the `typing._eval_type` function expects type params to be
|
| 125 |
+
# passed as a separate argument. However, internally, `_eval_type` calls
|
| 126 |
+
# `ForwardRef._evaluate` which will merge type params with the localns,
|
| 127 |
+
# essentially mimicking what we do here.
|
| 128 |
+
type_params: tuple[_TypeVarLike, ...] = getattr(obj, '__type_params__', ())
|
| 129 |
+
if parent_namespace is not None:
|
| 130 |
+
# We also fetch type params from the parent namespace. If present, it probably
|
| 131 |
+
# means the function was defined in a class. This is to support the following:
|
| 132 |
+
# https://github.com/python/cpython/issues/124089.
|
| 133 |
+
type_params += parent_namespace.get('__type_params__', ())
|
| 134 |
+
|
| 135 |
+
locals_list.append({t.__name__: t for t in type_params})
|
| 136 |
+
|
| 137 |
+
# What about short-circuiting to `obj.__globals__`?
|
| 138 |
+
globalns = get_module_ns_of(obj)
|
| 139 |
+
|
| 140 |
+
return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class NsResolver:
|
| 144 |
+
"""A class responsible for the namespaces resolving logic for annotations evaluation.
|
| 145 |
+
|
| 146 |
+
This class handles the namespace logic when evaluating annotations mainly for class objects.
|
| 147 |
+
|
| 148 |
+
It holds a stack of classes that are being inspected during the core schema building,
|
| 149 |
+
and the `types_namespace` property exposes the globals and locals to be used for
|
| 150 |
+
type annotation evaluation. Additionally -- if no class is present in the stack -- a
|
| 151 |
+
fallback globals and locals can be provided using the `namespaces_tuple` argument
|
| 152 |
+
(this is useful when generating a schema for a simple annotation, e.g. when using
|
| 153 |
+
`TypeAdapter`).
|
| 154 |
+
|
| 155 |
+
The namespace creation logic is unfortunately flawed in some cases, for backwards
|
| 156 |
+
compatibility reasons and to better support valid edge cases. See the description
|
| 157 |
+
for the `parent_namespace` argument and the example for more details.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
namespaces_tuple: The default globals and locals to use if no class is present
|
| 161 |
+
on the stack. This can be useful when using the `GenerateSchema` class
|
| 162 |
+
with `TypeAdapter`, where the "type" being analyzed is a simple annotation.
|
| 163 |
+
parent_namespace: An optional parent namespace that will be added to the locals
|
| 164 |
+
with the lowest priority. For a given class defined in a function, the locals
|
| 165 |
+
of this function are usually used as the parent namespace:
|
| 166 |
+
|
| 167 |
+
```python {lint="skip" test="skip"}
|
| 168 |
+
from pydantic import BaseModel
|
| 169 |
+
|
| 170 |
+
def func() -> None:
|
| 171 |
+
SomeType = int
|
| 172 |
+
|
| 173 |
+
class Model(BaseModel):
|
| 174 |
+
f: 'SomeType'
|
| 175 |
+
|
| 176 |
+
# when collecting fields, an namespace resolver instance will be created
|
| 177 |
+
# this way:
|
| 178 |
+
# ns_resolver = NsResolver(parent_namespace={'SomeType': SomeType})
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
For backwards compatibility reasons and to support valid edge cases, this parent
|
| 182 |
+
namespace will be used for *every* type being pushed to the stack. In the future,
|
| 183 |
+
we might want to be smarter by only doing so when the type being pushed is defined
|
| 184 |
+
in the same module as the parent namespace.
|
| 185 |
+
|
| 186 |
+
Example:
|
| 187 |
+
```python {lint="skip" test="skip"}
|
| 188 |
+
ns_resolver = NsResolver(
|
| 189 |
+
parent_namespace={'fallback': 1},
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
class Sub:
|
| 193 |
+
m: 'Model'
|
| 194 |
+
|
| 195 |
+
class Model:
|
| 196 |
+
some_local = 1
|
| 197 |
+
sub: Sub
|
| 198 |
+
|
| 199 |
+
ns_resolver = NsResolver()
|
| 200 |
+
|
| 201 |
+
# This is roughly what happens when we build a core schema for `Model`:
|
| 202 |
+
with ns_resolver.push(Model):
|
| 203 |
+
ns_resolver.types_namespace
|
| 204 |
+
#> NamespacesTuple({'Sub': Sub}, {'Model': Model, 'some_local': 1})
|
| 205 |
+
# First thing to notice here, the model being pushed is added to the locals.
|
| 206 |
+
# Because `NsResolver` is being used during the model definition, it is not
|
| 207 |
+
# yet added to the globals. This is useful when resolving self-referencing annotations.
|
| 208 |
+
|
| 209 |
+
with ns_resolver.push(Sub):
|
| 210 |
+
ns_resolver.types_namespace
|
| 211 |
+
#> NamespacesTuple({'Sub': Sub}, {'Sub': Sub, 'Model': Model})
|
| 212 |
+
# Second thing to notice: `Sub` is present in both the globals and locals.
|
| 213 |
+
# This is not an issue, just that as described above, the model being pushed
|
| 214 |
+
# is added to the locals, but it happens to be present in the globals as well
|
| 215 |
+
# because it is already defined.
|
| 216 |
+
# Third thing to notice: `Model` is also added in locals. This is a backwards
|
| 217 |
+
# compatibility workaround that allows for `Sub` to be able to resolve `'Model'`
|
| 218 |
+
# correctly (as otherwise models would have to be rebuilt even though this
|
| 219 |
+
# doesn't look necessary).
|
| 220 |
+
```
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
def __init__(
|
| 224 |
+
self,
|
| 225 |
+
namespaces_tuple: NamespacesTuple | None = None,
|
| 226 |
+
parent_namespace: MappingNamespace | None = None,
|
| 227 |
+
) -> None:
|
| 228 |
+
self._base_ns_tuple = namespaces_tuple or NamespacesTuple({}, {})
|
| 229 |
+
self._parent_ns = parent_namespace
|
| 230 |
+
self._types_stack: list[type[Any] | TypeAliasType] = []
|
| 231 |
+
|
| 232 |
+
@cached_property
|
| 233 |
+
def types_namespace(self) -> NamespacesTuple:
|
| 234 |
+
"""The current global and local namespaces to be used for annotations evaluation."""
|
| 235 |
+
if not self._types_stack:
|
| 236 |
+
# TODO: should we merge the parent namespace here?
|
| 237 |
+
# This is relevant for TypeAdapter, where there are no types on the stack, and we might
|
| 238 |
+
# need access to the parent_ns. Right now, we sidestep this in `type_adapter.py` by passing
|
| 239 |
+
# locals to both parent_ns and the base_ns_tuple, but this is a bit hacky.
|
| 240 |
+
# we might consider something like:
|
| 241 |
+
# if self._parent_ns is not None:
|
| 242 |
+
# # Hacky workarounds, see class docstring:
|
| 243 |
+
# # An optional parent namespace that will be added to the locals with the lowest priority
|
| 244 |
+
# locals_list: list[MappingNamespace] = [self._parent_ns, self._base_ns_tuple.locals]
|
| 245 |
+
# return NamespacesTuple(self._base_ns_tuple.globals, LazyLocalNamespace(*locals_list))
|
| 246 |
+
return self._base_ns_tuple
|
| 247 |
+
|
| 248 |
+
typ = self._types_stack[-1]
|
| 249 |
+
|
| 250 |
+
globalns = get_module_ns_of(typ)
|
| 251 |
+
|
| 252 |
+
locals_list: list[MappingNamespace] = []
|
| 253 |
+
# Hacky workarounds, see class docstring:
|
| 254 |
+
# An optional parent namespace that will be added to the locals with the lowest priority
|
| 255 |
+
if self._parent_ns is not None:
|
| 256 |
+
locals_list.append(self._parent_ns)
|
| 257 |
+
if len(self._types_stack) > 1:
|
| 258 |
+
first_type = self._types_stack[0]
|
| 259 |
+
locals_list.append({first_type.__name__: first_type})
|
| 260 |
+
|
| 261 |
+
# Adding `__type_params__` *before* `vars(typ)`, as the latter takes priority
|
| 262 |
+
# (see https://github.com/python/cpython/pull/120272).
|
| 263 |
+
# TODO `typ.__type_params__` when we drop support for Python 3.11:
|
| 264 |
+
type_params: tuple[_TypeVarLike, ...] = getattr(typ, '__type_params__', ())
|
| 265 |
+
if type_params:
|
| 266 |
+
# Adding `__type_params__` is mostly useful for generic classes defined using
|
| 267 |
+
# PEP 695 syntax *and* using forward annotations (see the example in
|
| 268 |
+
# https://github.com/python/cpython/issues/114053). For TypeAliasType instances,
|
| 269 |
+
# it is way less common, but still required if using a string annotation in the alias
|
| 270 |
+
# value, e.g. `type A[T] = 'T'` (which is not necessary in most cases).
|
| 271 |
+
locals_list.append({t.__name__: t for t in type_params})
|
| 272 |
+
|
| 273 |
+
# TypeAliasType instances don't have a `__dict__` attribute, so the check
|
| 274 |
+
# is necessary:
|
| 275 |
+
if hasattr(typ, '__dict__'):
|
| 276 |
+
locals_list.append(vars(typ))
|
| 277 |
+
|
| 278 |
+
# The `len(self._types_stack) > 1` check above prevents this from being added twice:
|
| 279 |
+
locals_list.append({typ.__name__: typ})
|
| 280 |
+
|
| 281 |
+
return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
|
| 282 |
+
|
| 283 |
+
@contextmanager
|
| 284 |
+
def push(self, typ: type[Any] | TypeAliasType, /) -> Generator[None]:
|
| 285 |
+
"""Push a type to the stack."""
|
| 286 |
+
self._types_stack.append(typ)
|
| 287 |
+
# Reset the cached property:
|
| 288 |
+
self.__dict__.pop('types_namespace', None)
|
| 289 |
+
try:
|
| 290 |
+
yield
|
| 291 |
+
finally:
|
| 292 |
+
self._types_stack.pop()
|
| 293 |
+
self.__dict__.pop('types_namespace', None)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_repr.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tools to provide pretty/human-readable display of objects."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
import types
|
| 6 |
+
from collections.abc import Callable, Collection, Generator, Iterable
|
| 7 |
+
from typing import TYPE_CHECKING, Any, ForwardRef, cast
|
| 8 |
+
|
| 9 |
+
import typing_extensions
|
| 10 |
+
from typing_extensions import TypeAlias
|
| 11 |
+
from typing_inspection import typing_objects
|
| 12 |
+
from typing_inspection.introspection import is_union_origin
|
| 13 |
+
|
| 14 |
+
from . import _typing_extra
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
# TODO remove type error comments when we drop support for Python 3.9
|
| 18 |
+
ReprArgs: TypeAlias = Iterable[tuple[str | None, Any]] # pyright: ignore[reportGeneralTypeIssues]
|
| 19 |
+
RichReprResult: TypeAlias = Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]] # pyright: ignore[reportGeneralTypeIssues]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PlainRepr(str):
|
| 23 |
+
"""String class where repr doesn't include quotes. Useful with Representation when you want to return a string
|
| 24 |
+
representation of something that is valid (or pseudo-valid) python.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __repr__(self) -> str:
|
| 28 |
+
return str(self)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Representation:
|
| 32 |
+
# Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods.
|
| 33 |
+
# `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/).
|
| 34 |
+
# `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html).
|
| 35 |
+
# (this is not a docstring to avoid adding a docstring to classes which inherit from Representation)
|
| 36 |
+
|
| 37 |
+
__slots__ = ()
|
| 38 |
+
|
| 39 |
+
def __repr_args__(self) -> ReprArgs:
|
| 40 |
+
"""Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| 41 |
+
|
| 42 |
+
Can either return:
|
| 43 |
+
* name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
|
| 44 |
+
* or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| 45 |
+
"""
|
| 46 |
+
attrs_names = cast(Collection[str], self.__slots__)
|
| 47 |
+
if not attrs_names and hasattr(self, '__dict__'):
|
| 48 |
+
attrs_names = self.__dict__.keys()
|
| 49 |
+
attrs = ((s, getattr(self, s)) for s in attrs_names)
|
| 50 |
+
return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None]
|
| 51 |
+
|
| 52 |
+
def __repr_name__(self) -> str:
|
| 53 |
+
"""Name of the instance's class, used in __repr__."""
|
| 54 |
+
return self.__class__.__name__
|
| 55 |
+
|
| 56 |
+
def __repr_recursion__(self, object: Any) -> str:
|
| 57 |
+
"""Returns the string representation of a recursive object."""
|
| 58 |
+
# This is copied over from the stdlib `pprint` module:
|
| 59 |
+
return f'<Recursion on {type(object).__name__} with id={id(object)}>'
|
| 60 |
+
|
| 61 |
+
def __repr_str__(self, join_str: str) -> str:
|
| 62 |
+
return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
|
| 63 |
+
|
| 64 |
+
def __pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any]:
|
| 65 |
+
"""Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects."""
|
| 66 |
+
yield self.__repr_name__() + '('
|
| 67 |
+
yield 1
|
| 68 |
+
for name, value in self.__repr_args__():
|
| 69 |
+
if name is not None:
|
| 70 |
+
yield name + '='
|
| 71 |
+
yield fmt(value)
|
| 72 |
+
yield ','
|
| 73 |
+
yield 0
|
| 74 |
+
yield -1
|
| 75 |
+
yield ')'
|
| 76 |
+
|
| 77 |
+
def __rich_repr__(self) -> RichReprResult:
|
| 78 |
+
"""Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects."""
|
| 79 |
+
for name, field_repr in self.__repr_args__():
|
| 80 |
+
if name is None:
|
| 81 |
+
yield field_repr
|
| 82 |
+
else:
|
| 83 |
+
yield name, field_repr
|
| 84 |
+
|
| 85 |
+
def __str__(self) -> str:
|
| 86 |
+
return self.__repr_str__(' ')
|
| 87 |
+
|
| 88 |
+
def __repr__(self) -> str:
|
| 89 |
+
return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def display_as_type(obj: Any) -> str:
|
| 93 |
+
"""Pretty representation of a type, should be as close as possible to the original type definition string.
|
| 94 |
+
|
| 95 |
+
Takes some logic from `typing._type_repr`.
|
| 96 |
+
"""
|
| 97 |
+
if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)):
|
| 98 |
+
return obj.__name__
|
| 99 |
+
elif obj is ...:
|
| 100 |
+
return '...'
|
| 101 |
+
elif isinstance(obj, Representation):
|
| 102 |
+
return repr(obj)
|
| 103 |
+
elif isinstance(obj, ForwardRef) or typing_objects.is_typealiastype(obj):
|
| 104 |
+
return str(obj)
|
| 105 |
+
|
| 106 |
+
if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)):
|
| 107 |
+
obj = obj.__class__
|
| 108 |
+
|
| 109 |
+
if is_union_origin(typing_extensions.get_origin(obj)):
|
| 110 |
+
args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
|
| 111 |
+
return f'Union[{args}]'
|
| 112 |
+
elif isinstance(obj, _typing_extra.WithArgsTypes):
|
| 113 |
+
if typing_objects.is_literal(typing_extensions.get_origin(obj)):
|
| 114 |
+
args = ', '.join(map(repr, typing_extensions.get_args(obj)))
|
| 115 |
+
else:
|
| 116 |
+
args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
|
| 117 |
+
try:
|
| 118 |
+
return f'{obj.__qualname__}[{args}]'
|
| 119 |
+
except AttributeError:
|
| 120 |
+
return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12
|
| 121 |
+
elif isinstance(obj, type):
|
| 122 |
+
return obj.__qualname__
|
| 123 |
+
else:
|
| 124 |
+
return repr(obj).replace('typing.', '').replace('typing_extensions.', '')
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_schema_gather.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pyright: reportTypedDictNotRequiredAccess=false, reportGeneralTypeIssues=false, reportArgumentType=false, reportAttributeAccessIssue=false
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import TypedDict
|
| 6 |
+
|
| 7 |
+
from pydantic_core.core_schema import ComputedField, CoreSchema, DefinitionReferenceSchema, SerSchema
|
| 8 |
+
from typing_extensions import TypeAlias
|
| 9 |
+
|
| 10 |
+
AllSchemas: TypeAlias = 'CoreSchema | SerSchema | ComputedField'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class GatherResult(TypedDict):
|
| 14 |
+
"""Schema traversing result."""
|
| 15 |
+
|
| 16 |
+
collected_references: dict[str, DefinitionReferenceSchema | None]
|
| 17 |
+
"""The collected definition references.
|
| 18 |
+
|
| 19 |
+
If a definition reference schema can be inlined, it means that there is
|
| 20 |
+
only one in the whole core schema. As such, it is stored as the value.
|
| 21 |
+
Otherwise, the value is set to `None`.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
deferred_discriminator_schemas: list[CoreSchema]
|
| 25 |
+
"""The list of core schemas having the discriminator application deferred."""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class MissingDefinitionError(LookupError):
|
| 29 |
+
"""A reference was pointing to a non-existing core schema."""
|
| 30 |
+
|
| 31 |
+
def __init__(self, schema_reference: str, /) -> None:
|
| 32 |
+
self.schema_reference = schema_reference
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class GatherContext:
|
| 37 |
+
"""The current context used during core schema traversing.
|
| 38 |
+
|
| 39 |
+
Context instances should only be used during schema traversing.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
definitions: dict[str, CoreSchema]
|
| 43 |
+
"""The available definitions."""
|
| 44 |
+
|
| 45 |
+
deferred_discriminator_schemas: list[CoreSchema] = field(init=False, default_factory=list)
|
| 46 |
+
"""The list of core schemas having the discriminator application deferred.
|
| 47 |
+
|
| 48 |
+
Internally, these core schemas have a specific key set in the core metadata dict.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
collected_references: dict[str, DefinitionReferenceSchema | None] = field(init=False, default_factory=dict)
|
| 52 |
+
"""The collected definition references.
|
| 53 |
+
|
| 54 |
+
If a definition reference schema can be inlined, it means that there is
|
| 55 |
+
only one in the whole core schema. As such, it is stored as the value.
|
| 56 |
+
Otherwise, the value is set to `None`.
|
| 57 |
+
|
| 58 |
+
During schema traversing, definition reference schemas can be added as candidates, or removed
|
| 59 |
+
(by setting the value to `None`).
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def traverse_metadata(schema: AllSchemas, ctx: GatherContext) -> None:
|
| 64 |
+
meta = schema.get('metadata')
|
| 65 |
+
if meta is not None and 'pydantic_internal_union_discriminator' in meta:
|
| 66 |
+
ctx.deferred_discriminator_schemas.append(schema) # pyright: ignore[reportArgumentType]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def traverse_definition_ref(def_ref_schema: DefinitionReferenceSchema, ctx: GatherContext) -> None:
|
| 70 |
+
schema_ref = def_ref_schema['schema_ref']
|
| 71 |
+
|
| 72 |
+
if schema_ref not in ctx.collected_references:
|
| 73 |
+
definition = ctx.definitions.get(schema_ref)
|
| 74 |
+
if definition is None:
|
| 75 |
+
raise MissingDefinitionError(schema_ref)
|
| 76 |
+
|
| 77 |
+
# The `'definition-ref'` schema was only encountered once, make it
|
| 78 |
+
# a candidate to be inlined:
|
| 79 |
+
ctx.collected_references[schema_ref] = def_ref_schema
|
| 80 |
+
traverse_schema(definition, ctx)
|
| 81 |
+
if 'serialization' in def_ref_schema:
|
| 82 |
+
traverse_schema(def_ref_schema['serialization'], ctx)
|
| 83 |
+
traverse_metadata(def_ref_schema, ctx)
|
| 84 |
+
else:
|
| 85 |
+
# The `'definition-ref'` schema was already encountered, meaning
|
| 86 |
+
# the previously encountered schema (and this one) can't be inlined:
|
| 87 |
+
ctx.collected_references[schema_ref] = None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def traverse_schema(schema: AllSchemas, context: GatherContext) -> None:
|
| 91 |
+
# TODO When we drop 3.9, use a match statement to get better type checking and remove
|
| 92 |
+
# file-level type ignore.
|
| 93 |
+
# (the `'type'` could also be fetched in every `if/elif` statement, but this alters performance).
|
| 94 |
+
schema_type = schema['type']
|
| 95 |
+
|
| 96 |
+
if schema_type == 'definition-ref':
|
| 97 |
+
traverse_definition_ref(schema, context)
|
| 98 |
+
# `traverse_definition_ref` handles the possible serialization and metadata schemas:
|
| 99 |
+
return
|
| 100 |
+
elif schema_type == 'definitions':
|
| 101 |
+
traverse_schema(schema['schema'], context)
|
| 102 |
+
for definition in schema['definitions']:
|
| 103 |
+
traverse_schema(definition, context)
|
| 104 |
+
elif schema_type in {'list', 'set', 'frozenset', 'generator'}:
|
| 105 |
+
if 'items_schema' in schema:
|
| 106 |
+
traverse_schema(schema['items_schema'], context)
|
| 107 |
+
elif schema_type == 'tuple':
|
| 108 |
+
if 'items_schema' in schema:
|
| 109 |
+
for s in schema['items_schema']:
|
| 110 |
+
traverse_schema(s, context)
|
| 111 |
+
elif schema_type == 'dict':
|
| 112 |
+
if 'keys_schema' in schema:
|
| 113 |
+
traverse_schema(schema['keys_schema'], context)
|
| 114 |
+
if 'values_schema' in schema:
|
| 115 |
+
traverse_schema(schema['values_schema'], context)
|
| 116 |
+
elif schema_type == 'union':
|
| 117 |
+
for choice in schema['choices']:
|
| 118 |
+
if isinstance(choice, tuple):
|
| 119 |
+
traverse_schema(choice[0], context)
|
| 120 |
+
else:
|
| 121 |
+
traverse_schema(choice, context)
|
| 122 |
+
elif schema_type == 'tagged-union':
|
| 123 |
+
for v in schema['choices'].values():
|
| 124 |
+
traverse_schema(v, context)
|
| 125 |
+
elif schema_type == 'chain':
|
| 126 |
+
for step in schema['steps']:
|
| 127 |
+
traverse_schema(step, context)
|
| 128 |
+
elif schema_type == 'lax-or-strict':
|
| 129 |
+
traverse_schema(schema['lax_schema'], context)
|
| 130 |
+
traverse_schema(schema['strict_schema'], context)
|
| 131 |
+
elif schema_type == 'json-or-python':
|
| 132 |
+
traverse_schema(schema['json_schema'], context)
|
| 133 |
+
traverse_schema(schema['python_schema'], context)
|
| 134 |
+
elif schema_type in {'model-fields', 'typed-dict'}:
|
| 135 |
+
if 'extras_schema' in schema:
|
| 136 |
+
traverse_schema(schema['extras_schema'], context)
|
| 137 |
+
if 'computed_fields' in schema:
|
| 138 |
+
for s in schema['computed_fields']:
|
| 139 |
+
traverse_schema(s, context)
|
| 140 |
+
for s in schema['fields'].values():
|
| 141 |
+
traverse_schema(s, context)
|
| 142 |
+
elif schema_type == 'dataclass-args':
|
| 143 |
+
if 'computed_fields' in schema:
|
| 144 |
+
for s in schema['computed_fields']:
|
| 145 |
+
traverse_schema(s, context)
|
| 146 |
+
for s in schema['fields']:
|
| 147 |
+
traverse_schema(s, context)
|
| 148 |
+
elif schema_type == 'arguments':
|
| 149 |
+
for s in schema['arguments_schema']:
|
| 150 |
+
traverse_schema(s['schema'], context)
|
| 151 |
+
if 'var_args_schema' in schema:
|
| 152 |
+
traverse_schema(schema['var_args_schema'], context)
|
| 153 |
+
if 'var_kwargs_schema' in schema:
|
| 154 |
+
traverse_schema(schema['var_kwargs_schema'], context)
|
| 155 |
+
elif schema_type == 'arguments-v3':
|
| 156 |
+
for s in schema['arguments_schema']:
|
| 157 |
+
traverse_schema(s['schema'], context)
|
| 158 |
+
elif schema_type == 'call':
|
| 159 |
+
traverse_schema(schema['arguments_schema'], context)
|
| 160 |
+
if 'return_schema' in schema:
|
| 161 |
+
traverse_schema(schema['return_schema'], context)
|
| 162 |
+
elif schema_type == 'computed-field':
|
| 163 |
+
traverse_schema(schema['return_schema'], context)
|
| 164 |
+
elif schema_type == 'function-before':
|
| 165 |
+
if 'schema' in schema:
|
| 166 |
+
traverse_schema(schema['schema'], context)
|
| 167 |
+
if 'json_schema_input_schema' in schema:
|
| 168 |
+
traverse_schema(schema['json_schema_input_schema'], context)
|
| 169 |
+
elif schema_type == 'function-plain':
|
| 170 |
+
# TODO duplicate schema types for serializers and validators, needs to be deduplicated.
|
| 171 |
+
if 'return_schema' in schema:
|
| 172 |
+
traverse_schema(schema['return_schema'], context)
|
| 173 |
+
if 'json_schema_input_schema' in schema:
|
| 174 |
+
traverse_schema(schema['json_schema_input_schema'], context)
|
| 175 |
+
elif schema_type == 'function-wrap':
|
| 176 |
+
# TODO duplicate schema types for serializers and validators, needs to be deduplicated.
|
| 177 |
+
if 'return_schema' in schema:
|
| 178 |
+
traverse_schema(schema['return_schema'], context)
|
| 179 |
+
if 'schema' in schema:
|
| 180 |
+
traverse_schema(schema['schema'], context)
|
| 181 |
+
if 'json_schema_input_schema' in schema:
|
| 182 |
+
traverse_schema(schema['json_schema_input_schema'], context)
|
| 183 |
+
else:
|
| 184 |
+
if 'schema' in schema:
|
| 185 |
+
traverse_schema(schema['schema'], context)
|
| 186 |
+
|
| 187 |
+
if 'serialization' in schema:
|
| 188 |
+
traverse_schema(schema['serialization'], context)
|
| 189 |
+
traverse_metadata(schema, context)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def gather_schemas_for_cleaning(schema: CoreSchema, definitions: dict[str, CoreSchema]) -> GatherResult:
|
| 193 |
+
"""Traverse the core schema and definitions and return the necessary information for schema cleaning.
|
| 194 |
+
|
| 195 |
+
During the core schema traversing, any `'definition-ref'` schema is:
|
| 196 |
+
|
| 197 |
+
- Validated: the reference must point to an existing definition. If this is not the case, a
|
| 198 |
+
`MissingDefinitionError` exception is raised.
|
| 199 |
+
- Stored in the context: the actual reference is stored in the context. Depending on whether
|
| 200 |
+
the `'definition-ref'` schema is encountered more that once, the schema itself is also
|
| 201 |
+
saved in the context to be inlined (i.e. replaced by the definition it points to).
|
| 202 |
+
"""
|
| 203 |
+
context = GatherContext(definitions)
|
| 204 |
+
traverse_schema(schema, context)
|
| 205 |
+
|
| 206 |
+
return {
|
| 207 |
+
'collected_references': context.collected_references,
|
| 208 |
+
'deferred_discriminator_schemas': context.deferred_discriminator_schemas,
|
| 209 |
+
}
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Types and utility functions used by various other internal tools."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Callable, Literal
|
| 6 |
+
|
| 7 |
+
from pydantic_core import core_schema
|
| 8 |
+
|
| 9 |
+
from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from ..json_schema import GenerateJsonSchema, JsonSchemaValue
|
| 13 |
+
from ._core_utils import CoreSchemaOrField
|
| 14 |
+
from ._generate_schema import GenerateSchema
|
| 15 |
+
from ._namespace_utils import NamespacesTuple
|
| 16 |
+
|
| 17 |
+
GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue]
|
| 18 |
+
HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class GenerateJsonSchemaHandler(GetJsonSchemaHandler):
|
| 22 |
+
"""JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
|
| 23 |
+
|
| 24 |
+
This is used for any Annotated metadata so that we don't end up with conflicting
|
| 25 |
+
modifications to the definition schema.
|
| 26 |
+
|
| 27 |
+
Used internally by Pydantic, please do not rely on this implementation.
|
| 28 |
+
See `GetJsonSchemaHandler` for the handler API.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
|
| 32 |
+
self.generate_json_schema = generate_json_schema
|
| 33 |
+
self.handler = handler_override or generate_json_schema.generate_inner
|
| 34 |
+
self.mode = generate_json_schema.mode
|
| 35 |
+
|
| 36 |
+
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
|
| 37 |
+
return self.handler(core_schema)
|
| 38 |
+
|
| 39 |
+
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
|
| 40 |
+
"""Resolves `$ref` in the json schema.
|
| 41 |
+
|
| 42 |
+
This returns the input json schema if there is no `$ref` in json schema.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
maybe_ref_json_schema: The input json schema that may contains `$ref`.
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
Resolved json schema.
|
| 49 |
+
|
| 50 |
+
Raises:
|
| 51 |
+
LookupError: If it can't find the definition for `$ref`.
|
| 52 |
+
"""
|
| 53 |
+
if '$ref' not in maybe_ref_json_schema:
|
| 54 |
+
return maybe_ref_json_schema
|
| 55 |
+
ref = maybe_ref_json_schema['$ref']
|
| 56 |
+
json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
|
| 57 |
+
if json_schema is None:
|
| 58 |
+
raise LookupError(
|
| 59 |
+
f'Could not find a ref for {ref}.'
|
| 60 |
+
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
|
| 61 |
+
)
|
| 62 |
+
return json_schema
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler):
|
| 66 |
+
"""Wrapper to use an arbitrary function as a `GetCoreSchemaHandler`.
|
| 67 |
+
|
| 68 |
+
Used internally by Pydantic, please do not rely on this implementation.
|
| 69 |
+
See `GetCoreSchemaHandler` for the handler API.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
handler: Callable[[Any], core_schema.CoreSchema],
|
| 75 |
+
generate_schema: GenerateSchema,
|
| 76 |
+
ref_mode: Literal['to-def', 'unpack'] = 'to-def',
|
| 77 |
+
) -> None:
|
| 78 |
+
self._handler = handler
|
| 79 |
+
self._generate_schema = generate_schema
|
| 80 |
+
self._ref_mode = ref_mode
|
| 81 |
+
|
| 82 |
+
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 83 |
+
schema = self._handler(source_type)
|
| 84 |
+
if self._ref_mode == 'to-def':
|
| 85 |
+
ref = schema.get('ref')
|
| 86 |
+
if ref is not None:
|
| 87 |
+
return self._generate_schema.defs.create_definition_reference_schema(schema)
|
| 88 |
+
return schema
|
| 89 |
+
else: # ref_mode = 'unpack'
|
| 90 |
+
return self.resolve_ref_schema(schema)
|
| 91 |
+
|
| 92 |
+
def _get_types_namespace(self) -> NamespacesTuple:
|
| 93 |
+
return self._generate_schema._types_namespace
|
| 94 |
+
|
| 95 |
+
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
|
| 96 |
+
return self._generate_schema.generate_schema(source_type)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def field_name(self) -> str | None:
|
| 100 |
+
return self._generate_schema.field_name_stack.get()
|
| 101 |
+
|
| 102 |
+
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
|
| 103 |
+
"""Resolves reference in the core schema.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
maybe_ref_schema: The input core schema that may contains reference.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Resolved core schema.
|
| 110 |
+
|
| 111 |
+
Raises:
|
| 112 |
+
LookupError: If it can't find the definition for reference.
|
| 113 |
+
"""
|
| 114 |
+
if maybe_ref_schema['type'] == 'definition-ref':
|
| 115 |
+
ref = maybe_ref_schema['schema_ref']
|
| 116 |
+
definition = self._generate_schema.defs.get_schema_from_ref(ref)
|
| 117 |
+
if definition is None:
|
| 118 |
+
raise LookupError(
|
| 119 |
+
f'Could not find a ref for {ref}.'
|
| 120 |
+
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
|
| 121 |
+
)
|
| 122 |
+
return definition
|
| 123 |
+
elif maybe_ref_schema['type'] == 'definitions':
|
| 124 |
+
return self.resolve_ref_schema(maybe_ref_schema['schema'])
|
| 125 |
+
return maybe_ref_schema
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_serializers.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import collections.abc
|
| 5 |
+
import typing
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from pydantic_core import PydanticOmit, core_schema
|
| 9 |
+
|
| 10 |
+
SEQUENCE_ORIGIN_MAP: dict[Any, Any] = {
|
| 11 |
+
typing.Deque: collections.deque, # noqa: UP006
|
| 12 |
+
collections.deque: collections.deque,
|
| 13 |
+
list: list,
|
| 14 |
+
typing.List: list, # noqa: UP006
|
| 15 |
+
tuple: tuple,
|
| 16 |
+
typing.Tuple: tuple, # noqa: UP006
|
| 17 |
+
set: set,
|
| 18 |
+
typing.AbstractSet: set,
|
| 19 |
+
typing.Set: set, # noqa: UP006
|
| 20 |
+
frozenset: frozenset,
|
| 21 |
+
typing.FrozenSet: frozenset, # noqa: UP006
|
| 22 |
+
typing.Sequence: list,
|
| 23 |
+
typing.MutableSequence: list,
|
| 24 |
+
typing.MutableSet: set,
|
| 25 |
+
# this doesn't handle subclasses of these
|
| 26 |
+
# parametrized typing.Set creates one of these
|
| 27 |
+
collections.abc.MutableSet: set,
|
| 28 |
+
collections.abc.Set: frozenset,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def serialize_sequence_via_list(
|
| 33 |
+
v: Any, handler: core_schema.SerializerFunctionWrapHandler, info: core_schema.SerializationInfo
|
| 34 |
+
) -> Any:
|
| 35 |
+
items: list[Any] = []
|
| 36 |
+
|
| 37 |
+
mapped_origin = SEQUENCE_ORIGIN_MAP.get(type(v), None)
|
| 38 |
+
if mapped_origin is None:
|
| 39 |
+
# we shouldn't hit this branch, should probably add a serialization error or something
|
| 40 |
+
return v
|
| 41 |
+
|
| 42 |
+
for index, item in enumerate(v):
|
| 43 |
+
try:
|
| 44 |
+
v = handler(item, index)
|
| 45 |
+
except PydanticOmit: # noqa: PERF203
|
| 46 |
+
pass
|
| 47 |
+
else:
|
| 48 |
+
items.append(v)
|
| 49 |
+
|
| 50 |
+
if info.mode_is_json():
|
| 51 |
+
return items
|
| 52 |
+
else:
|
| 53 |
+
return mapped_origin(items)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_signature.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
from typing import TYPE_CHECKING, Any, Callable
|
| 6 |
+
|
| 7 |
+
from pydantic_core import PydanticUndefined
|
| 8 |
+
|
| 9 |
+
from ._utils import is_valid_identifier
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from ..config import ExtraValues
|
| 13 |
+
from ..fields import FieldInfo
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Copied over from stdlib dataclasses
|
| 17 |
+
class _HAS_DEFAULT_FACTORY_CLASS:
|
| 18 |
+
def __repr__(self):
|
| 19 |
+
return '<factory>'
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _field_name_for_signature(field_name: str, field_info: FieldInfo) -> str:
|
| 26 |
+
"""Extract the correct name to use for the field when generating a signature.
|
| 27 |
+
|
| 28 |
+
Assuming the field has a valid alias, this will return the alias. Otherwise, it will return the field name.
|
| 29 |
+
First priority is given to the alias, then the validation_alias, then the field name.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
field_name: The name of the field
|
| 33 |
+
field_info: The corresponding FieldInfo object.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
The correct name to use when generating a signature.
|
| 37 |
+
"""
|
| 38 |
+
if isinstance(field_info.alias, str) and is_valid_identifier(field_info.alias):
|
| 39 |
+
return field_info.alias
|
| 40 |
+
if isinstance(field_info.validation_alias, str) and is_valid_identifier(field_info.validation_alias):
|
| 41 |
+
return field_info.validation_alias
|
| 42 |
+
|
| 43 |
+
return field_name
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _process_param_defaults(param: Parameter) -> Parameter:
|
| 47 |
+
"""Modify the signature for a parameter in a dataclass where the default value is a FieldInfo instance.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
param (Parameter): The parameter
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
Parameter: The custom processed parameter
|
| 54 |
+
"""
|
| 55 |
+
from ..fields import FieldInfo
|
| 56 |
+
|
| 57 |
+
param_default = param.default
|
| 58 |
+
if isinstance(param_default, FieldInfo):
|
| 59 |
+
annotation = param.annotation
|
| 60 |
+
# Replace the annotation if appropriate
|
| 61 |
+
# inspect does "clever" things to show annotations as strings because we have
|
| 62 |
+
# `from __future__ import annotations` in main, we don't want that
|
| 63 |
+
if annotation == 'Any':
|
| 64 |
+
annotation = Any
|
| 65 |
+
|
| 66 |
+
# Replace the field default
|
| 67 |
+
default = param_default.default
|
| 68 |
+
if default is PydanticUndefined:
|
| 69 |
+
if param_default.default_factory is PydanticUndefined:
|
| 70 |
+
default = Signature.empty
|
| 71 |
+
else:
|
| 72 |
+
# this is used by dataclasses to indicate a factory exists:
|
| 73 |
+
default = dataclasses._HAS_DEFAULT_FACTORY # type: ignore
|
| 74 |
+
return param.replace(
|
| 75 |
+
annotation=annotation, name=_field_name_for_signature(param.name, param_default), default=default
|
| 76 |
+
)
|
| 77 |
+
return param
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _generate_signature_parameters( # noqa: C901 (ignore complexity, could use a refactor)
|
| 81 |
+
init: Callable[..., None],
|
| 82 |
+
fields: dict[str, FieldInfo],
|
| 83 |
+
validate_by_name: bool,
|
| 84 |
+
extra: ExtraValues | None,
|
| 85 |
+
) -> dict[str, Parameter]:
|
| 86 |
+
"""Generate a mapping of parameter names to Parameter objects for a pydantic BaseModel or dataclass."""
|
| 87 |
+
from itertools import islice
|
| 88 |
+
|
| 89 |
+
present_params = signature(init).parameters.values()
|
| 90 |
+
merged_params: dict[str, Parameter] = {}
|
| 91 |
+
var_kw = None
|
| 92 |
+
use_var_kw = False
|
| 93 |
+
|
| 94 |
+
for param in islice(present_params, 1, None): # skip self arg
|
| 95 |
+
# inspect does "clever" things to show annotations as strings because we have
|
| 96 |
+
# `from __future__ import annotations` in main, we don't want that
|
| 97 |
+
if fields.get(param.name):
|
| 98 |
+
# exclude params with init=False
|
| 99 |
+
if getattr(fields[param.name], 'init', True) is False:
|
| 100 |
+
continue
|
| 101 |
+
param = param.replace(name=_field_name_for_signature(param.name, fields[param.name]))
|
| 102 |
+
if param.annotation == 'Any':
|
| 103 |
+
param = param.replace(annotation=Any)
|
| 104 |
+
if param.kind is param.VAR_KEYWORD:
|
| 105 |
+
var_kw = param
|
| 106 |
+
continue
|
| 107 |
+
merged_params[param.name] = param
|
| 108 |
+
|
| 109 |
+
if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through
|
| 110 |
+
allow_names = validate_by_name
|
| 111 |
+
for field_name, field in fields.items():
|
| 112 |
+
# when alias is a str it should be used for signature generation
|
| 113 |
+
param_name = _field_name_for_signature(field_name, field)
|
| 114 |
+
|
| 115 |
+
if field_name in merged_params or param_name in merged_params:
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
if not is_valid_identifier(param_name):
|
| 119 |
+
if allow_names:
|
| 120 |
+
param_name = field_name
|
| 121 |
+
else:
|
| 122 |
+
use_var_kw = True
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
if field.is_required():
|
| 126 |
+
default = Parameter.empty
|
| 127 |
+
elif field.default_factory is not None:
|
| 128 |
+
# Mimics stdlib dataclasses:
|
| 129 |
+
default = _HAS_DEFAULT_FACTORY
|
| 130 |
+
else:
|
| 131 |
+
default = field.default
|
| 132 |
+
merged_params[param_name] = Parameter(
|
| 133 |
+
param_name,
|
| 134 |
+
Parameter.KEYWORD_ONLY,
|
| 135 |
+
annotation=field.rebuild_annotation(),
|
| 136 |
+
default=default,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if extra == 'allow':
|
| 140 |
+
use_var_kw = True
|
| 141 |
+
|
| 142 |
+
if var_kw and use_var_kw:
|
| 143 |
+
# Make sure the parameter for extra kwargs
|
| 144 |
+
# does not have the same name as a field
|
| 145 |
+
default_model_signature = [
|
| 146 |
+
('self', Parameter.POSITIONAL_ONLY),
|
| 147 |
+
('data', Parameter.VAR_KEYWORD),
|
| 148 |
+
]
|
| 149 |
+
if [(p.name, p.kind) for p in present_params] == default_model_signature:
|
| 150 |
+
# if this is the standard model signature, use extra_data as the extra args name
|
| 151 |
+
var_kw_name = 'extra_data'
|
| 152 |
+
else:
|
| 153 |
+
# else start from var_kw
|
| 154 |
+
var_kw_name = var_kw.name
|
| 155 |
+
|
| 156 |
+
# generate a name that's definitely unique
|
| 157 |
+
while var_kw_name in fields:
|
| 158 |
+
var_kw_name += '_'
|
| 159 |
+
merged_params[var_kw_name] = var_kw.replace(name=var_kw_name)
|
| 160 |
+
|
| 161 |
+
return merged_params
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def generate_pydantic_signature(
|
| 165 |
+
init: Callable[..., None],
|
| 166 |
+
fields: dict[str, FieldInfo],
|
| 167 |
+
validate_by_name: bool,
|
| 168 |
+
extra: ExtraValues | None,
|
| 169 |
+
is_dataclass: bool = False,
|
| 170 |
+
) -> Signature:
|
| 171 |
+
"""Generate signature for a pydantic BaseModel or dataclass.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
init: The class init.
|
| 175 |
+
fields: The model fields.
|
| 176 |
+
validate_by_name: The `validate_by_name` value of the config.
|
| 177 |
+
extra: The `extra` value of the config.
|
| 178 |
+
is_dataclass: Whether the model is a dataclass.
|
| 179 |
+
|
| 180 |
+
Returns:
|
| 181 |
+
The dataclass/BaseModel subclass signature.
|
| 182 |
+
"""
|
| 183 |
+
merged_params = _generate_signature_parameters(init, fields, validate_by_name, extra)
|
| 184 |
+
|
| 185 |
+
if is_dataclass:
|
| 186 |
+
merged_params = {k: _process_param_defaults(v) for k, v in merged_params.items()}
|
| 187 |
+
|
| 188 |
+
return Signature(parameters=list(merged_params.values()), return_annotation=None)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_typing_extra.py
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logic for interacting with type annotations, mostly extensions, shims and hacks to wrap Python's typing module."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import collections.abc
|
| 6 |
+
import re
|
| 7 |
+
import sys
|
| 8 |
+
import types
|
| 9 |
+
import typing
|
| 10 |
+
from functools import partial
|
| 11 |
+
from typing import TYPE_CHECKING, Any, Callable, cast
|
| 12 |
+
|
| 13 |
+
import typing_extensions
|
| 14 |
+
from typing_extensions import deprecated, get_args, get_origin
|
| 15 |
+
from typing_inspection import typing_objects
|
| 16 |
+
from typing_inspection.introspection import is_union_origin
|
| 17 |
+
|
| 18 |
+
from pydantic.version import version_short
|
| 19 |
+
|
| 20 |
+
from ._namespace_utils import GlobalsNamespace, MappingNamespace, NsResolver, get_module_ns_of
|
| 21 |
+
|
| 22 |
+
if sys.version_info < (3, 10):
|
| 23 |
+
NoneType = type(None)
|
| 24 |
+
EllipsisType = type(Ellipsis)
|
| 25 |
+
else:
|
| 26 |
+
from types import EllipsisType as EllipsisType
|
| 27 |
+
from types import NoneType as NoneType
|
| 28 |
+
|
| 29 |
+
if sys.version_info >= (3, 14):
|
| 30 |
+
import annotationlib
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from pydantic import BaseModel
|
| 34 |
+
|
| 35 |
+
# As per https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types,
|
| 36 |
+
# always check for both `typing` and `typing_extensions` variants of a typing construct.
|
| 37 |
+
# (this is implemented differently than the suggested approach in the `typing_extensions`
|
| 38 |
+
# docs for performance).
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_t_annotated = typing.Annotated
|
| 42 |
+
_te_annotated = typing_extensions.Annotated
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def is_annotated(tp: Any, /) -> bool:
|
| 46 |
+
"""Return whether the provided argument is a `Annotated` special form.
|
| 47 |
+
|
| 48 |
+
```python {test="skip" lint="skip"}
|
| 49 |
+
is_annotated(Annotated[int, ...])
|
| 50 |
+
#> True
|
| 51 |
+
```
|
| 52 |
+
"""
|
| 53 |
+
origin = get_origin(tp)
|
| 54 |
+
return origin is _t_annotated or origin is _te_annotated
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def annotated_type(tp: Any, /) -> Any | None:
|
| 58 |
+
"""Return the type of the `Annotated` special form, or `None`."""
|
| 59 |
+
return tp.__origin__ if typing_objects.is_annotated(get_origin(tp)) else None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def unpack_type(tp: Any, /) -> Any | None:
|
| 63 |
+
"""Return the type wrapped by the `Unpack` special form, or `None`."""
|
| 64 |
+
return get_args(tp)[0] if typing_objects.is_unpack(get_origin(tp)) else None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def is_hashable(tp: Any, /) -> bool:
|
| 68 |
+
"""Return whether the provided argument is the `Hashable` class.
|
| 69 |
+
|
| 70 |
+
```python {test="skip" lint="skip"}
|
| 71 |
+
is_hashable(Hashable)
|
| 72 |
+
#> True
|
| 73 |
+
```
|
| 74 |
+
"""
|
| 75 |
+
# `get_origin` is documented as normalizing any typing-module aliases to `collections` classes,
|
| 76 |
+
# hence the second check:
|
| 77 |
+
return tp is collections.abc.Hashable or get_origin(tp) is collections.abc.Hashable
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def is_callable(tp: Any, /) -> bool:
|
| 81 |
+
"""Return whether the provided argument is a `Callable`, parametrized or not.
|
| 82 |
+
|
| 83 |
+
```python {test="skip" lint="skip"}
|
| 84 |
+
is_callable(Callable[[int], str])
|
| 85 |
+
#> True
|
| 86 |
+
is_callable(typing.Callable)
|
| 87 |
+
#> True
|
| 88 |
+
is_callable(collections.abc.Callable)
|
| 89 |
+
#> True
|
| 90 |
+
```
|
| 91 |
+
"""
|
| 92 |
+
# `get_origin` is documented as normalizing any typing-module aliases to `collections` classes,
|
| 93 |
+
# hence the second check:
|
| 94 |
+
return tp is collections.abc.Callable or get_origin(tp) is collections.abc.Callable
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
_classvar_re = re.compile(r'((\w+\.)?Annotated\[)?(\w+\.)?ClassVar\[')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def is_classvar_annotation(tp: Any, /) -> bool:
|
| 101 |
+
"""Return whether the provided argument represents a class variable annotation.
|
| 102 |
+
|
| 103 |
+
Although not explicitly stated by the typing specification, `ClassVar` can be used
|
| 104 |
+
inside `Annotated` and as such, this function checks for this specific scenario.
|
| 105 |
+
|
| 106 |
+
Because this function is used to detect class variables before evaluating forward references
|
| 107 |
+
(or because evaluation failed), we also implement a naive regex match implementation. This is
|
| 108 |
+
required because class variables are inspected before fields are collected, so we try to be
|
| 109 |
+
as accurate as possible.
|
| 110 |
+
"""
|
| 111 |
+
if typing_objects.is_classvar(tp):
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
origin = get_origin(tp)
|
| 115 |
+
|
| 116 |
+
if typing_objects.is_classvar(origin):
|
| 117 |
+
return True
|
| 118 |
+
|
| 119 |
+
if typing_objects.is_annotated(origin):
|
| 120 |
+
annotated_type = tp.__origin__
|
| 121 |
+
if typing_objects.is_classvar(annotated_type) or typing_objects.is_classvar(get_origin(annotated_type)):
|
| 122 |
+
return True
|
| 123 |
+
|
| 124 |
+
str_ann: str | None = None
|
| 125 |
+
if isinstance(tp, typing.ForwardRef):
|
| 126 |
+
str_ann = tp.__forward_arg__
|
| 127 |
+
if isinstance(tp, str):
|
| 128 |
+
str_ann = tp
|
| 129 |
+
|
| 130 |
+
if str_ann is not None and _classvar_re.match(str_ann):
|
| 131 |
+
# stdlib dataclasses do something similar, although a bit more advanced
|
| 132 |
+
# (see `dataclass._is_type`).
|
| 133 |
+
return True
|
| 134 |
+
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
_t_final = typing.Final
|
| 139 |
+
_te_final = typing_extensions.Final
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# TODO implement `is_finalvar_annotation` as Final can be wrapped with other special forms:
|
| 143 |
+
def is_finalvar(tp: Any, /) -> bool:
|
| 144 |
+
"""Return whether the provided argument is a `Final` special form, parametrized or not.
|
| 145 |
+
|
| 146 |
+
```python {test="skip" lint="skip"}
|
| 147 |
+
is_finalvar(Final[int])
|
| 148 |
+
#> True
|
| 149 |
+
is_finalvar(Final)
|
| 150 |
+
#> True
|
| 151 |
+
"""
|
| 152 |
+
# Final is not necessarily parametrized:
|
| 153 |
+
if tp is _t_final or tp is _te_final:
|
| 154 |
+
return True
|
| 155 |
+
origin = get_origin(tp)
|
| 156 |
+
return origin is _t_final or origin is _te_final
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
_NONE_TYPES: tuple[Any, ...] = (None, NoneType, typing.Literal[None], typing_extensions.Literal[None])
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def is_none_type(tp: Any, /) -> bool:
|
| 163 |
+
"""Return whether the argument represents the `None` type as part of an annotation.
|
| 164 |
+
|
| 165 |
+
```python {test="skip" lint="skip"}
|
| 166 |
+
is_none_type(None)
|
| 167 |
+
#> True
|
| 168 |
+
is_none_type(NoneType)
|
| 169 |
+
#> True
|
| 170 |
+
is_none_type(Literal[None])
|
| 171 |
+
#> True
|
| 172 |
+
is_none_type(type[None])
|
| 173 |
+
#> False
|
| 174 |
+
"""
|
| 175 |
+
return tp in _NONE_TYPES
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def is_namedtuple(tp: Any, /) -> bool:
|
| 179 |
+
"""Return whether the provided argument is a named tuple class.
|
| 180 |
+
|
| 181 |
+
The class can be created using `typing.NamedTuple` or `collections.namedtuple`.
|
| 182 |
+
Parametrized generic classes are *not* assumed to be named tuples.
|
| 183 |
+
"""
|
| 184 |
+
from ._utils import lenient_issubclass # circ. import
|
| 185 |
+
|
| 186 |
+
return lenient_issubclass(tp, tuple) and hasattr(tp, '_fields')
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# TODO In 2.12, delete this export. It is currently defined only to not break
|
| 190 |
+
# pydantic-settings which relies on it:
|
| 191 |
+
origin_is_union = is_union_origin
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def is_generic_alias(tp: Any, /) -> bool:
|
| 195 |
+
return isinstance(tp, (types.GenericAlias, typing._GenericAlias)) # pyright: ignore[reportAttributeAccessIssue]
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# TODO: Ideally, we should avoid relying on the private `typing` constructs:
|
| 199 |
+
|
| 200 |
+
if sys.version_info < (3, 10):
|
| 201 |
+
WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias) # pyright: ignore[reportAttributeAccessIssue]
|
| 202 |
+
else:
|
| 203 |
+
WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias, types.UnionType) # pyright: ignore[reportAttributeAccessIssue]
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# Similarly, we shouldn't rely on this `_Final` class, which is even more private than `_GenericAlias`:
|
| 207 |
+
typing_base: Any = typing._Final # pyright: ignore[reportAttributeAccessIssue]
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
### Annotation evaluations functions:
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def parent_frame_namespace(*, parent_depth: int = 2, force: bool = False) -> dict[str, Any] | None:
|
| 214 |
+
"""Fetch the local namespace of the parent frame where this function is called.
|
| 215 |
+
|
| 216 |
+
Using this function is mostly useful to resolve forward annotations pointing to members defined in a local namespace,
|
| 217 |
+
such as assignments inside a function. Using the standard library tools, it is currently not possible to resolve
|
| 218 |
+
such annotations:
|
| 219 |
+
|
| 220 |
+
```python {lint="skip" test="skip"}
|
| 221 |
+
from typing import get_type_hints
|
| 222 |
+
|
| 223 |
+
def func() -> None:
|
| 224 |
+
Alias = int
|
| 225 |
+
|
| 226 |
+
class C:
|
| 227 |
+
a: 'Alias'
|
| 228 |
+
|
| 229 |
+
# Raises a `NameError: 'Alias' is not defined`
|
| 230 |
+
get_type_hints(C)
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
Pydantic uses this function when a Pydantic model is being defined to fetch the parent frame locals. However,
|
| 234 |
+
this only allows us to fetch the parent frame namespace and not other parents (e.g. a model defined in a function,
|
| 235 |
+
itself defined in another function). Inspecting the next outer frames (using `f_back`) is not reliable enough
|
| 236 |
+
(see https://discuss.python.org/t/20659).
|
| 237 |
+
|
| 238 |
+
Because this function is mostly used to better resolve forward annotations, nothing is returned if the parent frame's
|
| 239 |
+
code object is defined at the module level. In this case, the locals of the frame will be the same as the module
|
| 240 |
+
globals where the class is defined (see `_namespace_utils.get_module_ns_of`). However, if you still want to fetch
|
| 241 |
+
the module globals (e.g. when rebuilding a model, where the frame where the rebuild call is performed might contain
|
| 242 |
+
members that you want to use for forward annotations evaluation), you can use the `force` parameter.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
parent_depth: The depth at which to get the frame. Defaults to 2, meaning the parent frame where this function
|
| 246 |
+
is called will be used.
|
| 247 |
+
force: Whether to always return the frame locals, even if the frame's code object is defined at the module level.
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
The locals of the namespace, or `None` if it was skipped as per the described logic.
|
| 251 |
+
"""
|
| 252 |
+
frame = sys._getframe(parent_depth)
|
| 253 |
+
|
| 254 |
+
if frame.f_code.co_name.startswith('<generic parameters of'):
|
| 255 |
+
# As `parent_frame_namespace` is mostly called in `ModelMetaclass.__new__`,
|
| 256 |
+
# the parent frame can be the annotation scope if the PEP 695 generic syntax is used.
|
| 257 |
+
# (see https://docs.python.org/3/reference/executionmodel.html#annotation-scopes,
|
| 258 |
+
# https://docs.python.org/3/reference/compound_stmts.html#generic-classes).
|
| 259 |
+
# In this case, the code name is set to `<generic parameters of MyClass>`,
|
| 260 |
+
# and we need to skip this frame as it is irrelevant.
|
| 261 |
+
frame = cast(types.FrameType, frame.f_back) # guaranteed to not be `None`
|
| 262 |
+
|
| 263 |
+
# note, we don't copy frame.f_locals here (or during the last return call), because we don't expect the namespace to be
|
| 264 |
+
# modified down the line if this becomes a problem, we could implement some sort of frozen mapping structure to enforce this.
|
| 265 |
+
if force:
|
| 266 |
+
return frame.f_locals
|
| 267 |
+
|
| 268 |
+
# If either of the following conditions are true, the class is defined at the top module level.
|
| 269 |
+
# To better understand why we need both of these checks, see
|
| 270 |
+
# https://github.com/pydantic/pydantic/pull/10113#discussion_r1714981531.
|
| 271 |
+
if frame.f_back is None or frame.f_code.co_name == '<module>':
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
return frame.f_locals
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def _type_convert(arg: Any) -> Any:
|
| 278 |
+
"""Convert `None` to `NoneType` and strings to `ForwardRef` instances.
|
| 279 |
+
|
| 280 |
+
This is a backport of the private `typing._type_convert` function. When
|
| 281 |
+
evaluating a type, `ForwardRef._evaluate` ends up being called, and is
|
| 282 |
+
responsible for making this conversion. However, we still have to apply
|
| 283 |
+
it for the first argument passed to our type evaluation functions, similarly
|
| 284 |
+
to the `typing.get_type_hints` function.
|
| 285 |
+
"""
|
| 286 |
+
if arg is None:
|
| 287 |
+
return NoneType
|
| 288 |
+
if isinstance(arg, str):
|
| 289 |
+
# Like `typing.get_type_hints`, assume the arg can be in any context,
|
| 290 |
+
# hence the proper `is_argument` and `is_class` args:
|
| 291 |
+
return _make_forward_ref(arg, is_argument=False, is_class=True)
|
| 292 |
+
return arg
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def safe_get_annotations(cls: type[Any]) -> dict[str, Any]:
|
| 296 |
+
"""Get the annotations for the provided class, accounting for potential deferred forward references.
|
| 297 |
+
|
| 298 |
+
Starting with Python 3.14, accessing the `__annotations__` attribute might raise a `NameError` if
|
| 299 |
+
a referenced symbol isn't defined yet. In this case, we return the annotation in the *forward ref*
|
| 300 |
+
format.
|
| 301 |
+
"""
|
| 302 |
+
if sys.version_info >= (3, 14):
|
| 303 |
+
return annotationlib.get_annotations(cls, format=annotationlib.Format.FORWARDREF)
|
| 304 |
+
else:
|
| 305 |
+
return cls.__dict__.get('__annotations__', {})
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def get_model_type_hints(
|
| 309 |
+
obj: type[BaseModel],
|
| 310 |
+
*,
|
| 311 |
+
ns_resolver: NsResolver | None = None,
|
| 312 |
+
) -> dict[str, tuple[Any, bool]]:
|
| 313 |
+
"""Collect annotations from a Pydantic model class, including those from parent classes.
|
| 314 |
+
|
| 315 |
+
Args:
|
| 316 |
+
obj: The Pydantic model to inspect.
|
| 317 |
+
ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.
|
| 318 |
+
|
| 319 |
+
Returns:
|
| 320 |
+
A dictionary mapping annotation names to a two-tuple: the first element is the evaluated
|
| 321 |
+
type or the original annotation if a `NameError` occurred, the second element is a boolean
|
| 322 |
+
indicating if whether the evaluation succeeded.
|
| 323 |
+
"""
|
| 324 |
+
hints: dict[str, Any] | dict[str, tuple[Any, bool]] = {}
|
| 325 |
+
ns_resolver = ns_resolver or NsResolver()
|
| 326 |
+
|
| 327 |
+
for base in reversed(obj.__mro__):
|
| 328 |
+
# For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals
|
| 329 |
+
# from the ns_resolver, but we want to be able to know which specific field failed
|
| 330 |
+
# to evaluate:
|
| 331 |
+
ann = safe_get_annotations(base)
|
| 332 |
+
|
| 333 |
+
if not ann:
|
| 334 |
+
continue
|
| 335 |
+
|
| 336 |
+
with ns_resolver.push(base):
|
| 337 |
+
globalns, localns = ns_resolver.types_namespace
|
| 338 |
+
for name, value in ann.items():
|
| 339 |
+
if name.startswith('_'):
|
| 340 |
+
# For private attributes, we only need the annotation to detect the `ClassVar` special form.
|
| 341 |
+
# For this reason, we still try to evaluate it, but we also catch any possible exception (on
|
| 342 |
+
# top of the `NameError`s caught in `try_eval_type`) that could happen so that users are free
|
| 343 |
+
# to use any kind of forward annotation for private fields (e.g. circular imports, new typing
|
| 344 |
+
# syntax, etc).
|
| 345 |
+
try:
|
| 346 |
+
hints[name] = try_eval_type(value, globalns, localns)
|
| 347 |
+
except Exception:
|
| 348 |
+
hints[name] = (value, False)
|
| 349 |
+
else:
|
| 350 |
+
hints[name] = try_eval_type(value, globalns, localns)
|
| 351 |
+
return hints
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def get_cls_type_hints(
|
| 355 |
+
obj: type[Any],
|
| 356 |
+
*,
|
| 357 |
+
ns_resolver: NsResolver | None = None,
|
| 358 |
+
) -> dict[str, Any]:
|
| 359 |
+
"""Collect annotations from a class, including those from parent classes.
|
| 360 |
+
|
| 361 |
+
Args:
|
| 362 |
+
obj: The class to inspect.
|
| 363 |
+
ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.
|
| 364 |
+
"""
|
| 365 |
+
hints: dict[str, Any] = {}
|
| 366 |
+
ns_resolver = ns_resolver or NsResolver()
|
| 367 |
+
|
| 368 |
+
for base in reversed(obj.__mro__):
|
| 369 |
+
# For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals
|
| 370 |
+
# from the ns_resolver, but we want to be able to know which specific field failed
|
| 371 |
+
# to evaluate:
|
| 372 |
+
ann = safe_get_annotations(base)
|
| 373 |
+
|
| 374 |
+
if not ann:
|
| 375 |
+
continue
|
| 376 |
+
|
| 377 |
+
with ns_resolver.push(base):
|
| 378 |
+
globalns, localns = ns_resolver.types_namespace
|
| 379 |
+
for name, value in ann.items():
|
| 380 |
+
hints[name] = eval_type(value, globalns, localns)
|
| 381 |
+
return hints
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def try_eval_type(
|
| 385 |
+
value: Any,
|
| 386 |
+
globalns: GlobalsNamespace | None = None,
|
| 387 |
+
localns: MappingNamespace | None = None,
|
| 388 |
+
) -> tuple[Any, bool]:
|
| 389 |
+
"""Try evaluating the annotation using the provided namespaces.
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
|
| 393 |
+
of `str`, it will be converted to a `ForwardRef`.
|
| 394 |
+
localns: The global namespace to use during annotation evaluation.
|
| 395 |
+
globalns: The local namespace to use during annotation evaluation.
|
| 396 |
+
|
| 397 |
+
Returns:
|
| 398 |
+
A two-tuple containing the possibly evaluated type and a boolean indicating
|
| 399 |
+
whether the evaluation succeeded or not.
|
| 400 |
+
"""
|
| 401 |
+
value = _type_convert(value)
|
| 402 |
+
|
| 403 |
+
try:
|
| 404 |
+
return eval_type_backport(value, globalns, localns), True
|
| 405 |
+
except NameError:
|
| 406 |
+
return value, False
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def eval_type(
|
| 410 |
+
value: Any,
|
| 411 |
+
globalns: GlobalsNamespace | None = None,
|
| 412 |
+
localns: MappingNamespace | None = None,
|
| 413 |
+
) -> Any:
|
| 414 |
+
"""Evaluate the annotation using the provided namespaces.
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
|
| 418 |
+
of `str`, it will be converted to a `ForwardRef`.
|
| 419 |
+
localns: The global namespace to use during annotation evaluation.
|
| 420 |
+
globalns: The local namespace to use during annotation evaluation.
|
| 421 |
+
"""
|
| 422 |
+
value = _type_convert(value)
|
| 423 |
+
return eval_type_backport(value, globalns, localns)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
@deprecated(
|
| 427 |
+
'`eval_type_lenient` is deprecated, use `try_eval_type` instead.',
|
| 428 |
+
category=None,
|
| 429 |
+
)
|
| 430 |
+
def eval_type_lenient(
|
| 431 |
+
value: Any,
|
| 432 |
+
globalns: GlobalsNamespace | None = None,
|
| 433 |
+
localns: MappingNamespace | None = None,
|
| 434 |
+
) -> Any:
|
| 435 |
+
ev, _ = try_eval_type(value, globalns, localns)
|
| 436 |
+
return ev
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def eval_type_backport(
|
| 440 |
+
value: Any,
|
| 441 |
+
globalns: GlobalsNamespace | None = None,
|
| 442 |
+
localns: MappingNamespace | None = None,
|
| 443 |
+
type_params: tuple[Any, ...] | None = None,
|
| 444 |
+
) -> Any:
|
| 445 |
+
"""An enhanced version of `typing._eval_type` which will fall back to using the `eval_type_backport`
|
| 446 |
+
package if it's installed to let older Python versions use newer typing constructs.
|
| 447 |
+
|
| 448 |
+
Specifically, this transforms `X | Y` into `typing.Union[X, Y]` and `list[X]` into `typing.List[X]`
|
| 449 |
+
(as well as all the types made generic in PEP 585) if the original syntax is not supported in the
|
| 450 |
+
current Python version.
|
| 451 |
+
|
| 452 |
+
This function will also display a helpful error if the value passed fails to evaluate.
|
| 453 |
+
"""
|
| 454 |
+
try:
|
| 455 |
+
return _eval_type_backport(value, globalns, localns, type_params)
|
| 456 |
+
except TypeError as e:
|
| 457 |
+
if 'Unable to evaluate type annotation' in str(e):
|
| 458 |
+
raise
|
| 459 |
+
|
| 460 |
+
# If it is a `TypeError` and value isn't a `ForwardRef`, it would have failed during annotation definition.
|
| 461 |
+
# Thus we assert here for type checking purposes:
|
| 462 |
+
assert isinstance(value, typing.ForwardRef)
|
| 463 |
+
|
| 464 |
+
message = f'Unable to evaluate type annotation {value.__forward_arg__!r}.'
|
| 465 |
+
if sys.version_info >= (3, 11):
|
| 466 |
+
e.add_note(message)
|
| 467 |
+
raise
|
| 468 |
+
else:
|
| 469 |
+
raise TypeError(message) from e
|
| 470 |
+
except RecursionError as e:
|
| 471 |
+
# TODO ideally recursion errors should be checked in `eval_type` above, but `eval_type_backport`
|
| 472 |
+
# is used directly in some places.
|
| 473 |
+
message = (
|
| 474 |
+
"If you made use of an implicit recursive type alias (e.g. `MyType = list['MyType']), "
|
| 475 |
+
'consider using PEP 695 type aliases instead. For more details, refer to the documentation: '
|
| 476 |
+
f'https://docs.pydantic.dev/{version_short()}/concepts/types/#named-recursive-types'
|
| 477 |
+
)
|
| 478 |
+
if sys.version_info >= (3, 11):
|
| 479 |
+
e.add_note(message)
|
| 480 |
+
raise
|
| 481 |
+
else:
|
| 482 |
+
raise RecursionError(f'{e.args[0]}\n{message}')
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _eval_type_backport(
|
| 486 |
+
value: Any,
|
| 487 |
+
globalns: GlobalsNamespace | None = None,
|
| 488 |
+
localns: MappingNamespace | None = None,
|
| 489 |
+
type_params: tuple[Any, ...] | None = None,
|
| 490 |
+
) -> Any:
|
| 491 |
+
try:
|
| 492 |
+
return _eval_type(value, globalns, localns, type_params)
|
| 493 |
+
except TypeError as e:
|
| 494 |
+
if not (isinstance(value, typing.ForwardRef) and is_backport_fixable_error(e)):
|
| 495 |
+
raise
|
| 496 |
+
|
| 497 |
+
try:
|
| 498 |
+
from eval_type_backport import eval_type_backport
|
| 499 |
+
except ImportError:
|
| 500 |
+
raise TypeError(
|
| 501 |
+
f'Unable to evaluate type annotation {value.__forward_arg__!r}. If you are making use '
|
| 502 |
+
'of the new typing syntax (unions using `|` since Python 3.10 or builtins subscripting '
|
| 503 |
+
'since Python 3.9), you should either replace the use of new syntax with the existing '
|
| 504 |
+
'`typing` constructs or install the `eval_type_backport` package.'
|
| 505 |
+
) from e
|
| 506 |
+
|
| 507 |
+
return eval_type_backport(
|
| 508 |
+
value,
|
| 509 |
+
globalns,
|
| 510 |
+
localns, # pyright: ignore[reportArgumentType], waiting on a new `eval_type_backport` release.
|
| 511 |
+
try_default=False,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def _eval_type(
|
| 516 |
+
value: Any,
|
| 517 |
+
globalns: GlobalsNamespace | None = None,
|
| 518 |
+
localns: MappingNamespace | None = None,
|
| 519 |
+
type_params: tuple[Any, ...] | None = None,
|
| 520 |
+
) -> Any:
|
| 521 |
+
if sys.version_info >= (3, 14):
|
| 522 |
+
# Starting in 3.14, `_eval_type()` does *not* apply `_type_convert()`
|
| 523 |
+
# anymore. This means the `None` -> `type(None)` conversion does not apply:
|
| 524 |
+
evaluated = typing._eval_type( # type: ignore
|
| 525 |
+
value,
|
| 526 |
+
globalns,
|
| 527 |
+
localns,
|
| 528 |
+
type_params=type_params,
|
| 529 |
+
# This is relevant when evaluating types from `TypedDict` classes, where string annotations
|
| 530 |
+
# are automatically converted to `ForwardRef` instances with a module set. In this case,
|
| 531 |
+
# Our `globalns` is irrelevant and we need to indicate `typing._eval_type()` that it should
|
| 532 |
+
# infer it from the `ForwardRef.__forward_module__` attribute instead (`typing.get_type_hints()`
|
| 533 |
+
# does the same). Note that this would probably be unnecessary if we properly iterated over the
|
| 534 |
+
# `__orig_bases__` for TypedDicts in `get_cls_type_hints()`:
|
| 535 |
+
prefer_fwd_module=True,
|
| 536 |
+
)
|
| 537 |
+
if evaluated is None:
|
| 538 |
+
evaluated = type(None)
|
| 539 |
+
return evaluated
|
| 540 |
+
elif sys.version_info >= (3, 13):
|
| 541 |
+
return typing._eval_type( # type: ignore
|
| 542 |
+
value, globalns, localns, type_params=type_params
|
| 543 |
+
)
|
| 544 |
+
else:
|
| 545 |
+
return typing._eval_type( # type: ignore
|
| 546 |
+
value, globalns, localns
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def is_backport_fixable_error(e: TypeError) -> bool:
|
| 551 |
+
msg = str(e)
|
| 552 |
+
|
| 553 |
+
return sys.version_info < (3, 10) and msg.startswith('unsupported operand type(s) for |: ')
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def get_function_type_hints(
|
| 557 |
+
function: Callable[..., Any],
|
| 558 |
+
*,
|
| 559 |
+
include_keys: set[str] | None = None,
|
| 560 |
+
globalns: GlobalsNamespace | None = None,
|
| 561 |
+
localns: MappingNamespace | None = None,
|
| 562 |
+
) -> dict[str, Any]:
|
| 563 |
+
"""Return type hints for a function.
|
| 564 |
+
|
| 565 |
+
This is similar to the `typing.get_type_hints` function, with a few differences:
|
| 566 |
+
- Support `functools.partial` by using the underlying `func` attribute.
|
| 567 |
+
- Do not wrap type annotation of a parameter with `Optional` if it has a default value of `None`
|
| 568 |
+
(related bug: https://github.com/python/cpython/issues/90353, only fixed in 3.11+).
|
| 569 |
+
"""
|
| 570 |
+
try:
|
| 571 |
+
if isinstance(function, partial):
|
| 572 |
+
annotations = function.func.__annotations__
|
| 573 |
+
else:
|
| 574 |
+
annotations = function.__annotations__
|
| 575 |
+
except AttributeError:
|
| 576 |
+
# Some functions (e.g. builtins) don't have annotations:
|
| 577 |
+
return {}
|
| 578 |
+
|
| 579 |
+
if globalns is None:
|
| 580 |
+
globalns = get_module_ns_of(function)
|
| 581 |
+
type_params: tuple[Any, ...] | None = None
|
| 582 |
+
if localns is None:
|
| 583 |
+
# If localns was specified, it is assumed to already contain type params. This is because
|
| 584 |
+
# Pydantic has more advanced logic to do so (see `_namespace_utils.ns_for_function`).
|
| 585 |
+
type_params = getattr(function, '__type_params__', ())
|
| 586 |
+
|
| 587 |
+
type_hints = {}
|
| 588 |
+
for name, value in annotations.items():
|
| 589 |
+
if include_keys is not None and name not in include_keys:
|
| 590 |
+
continue
|
| 591 |
+
if value is None:
|
| 592 |
+
value = NoneType
|
| 593 |
+
elif isinstance(value, str):
|
| 594 |
+
value = _make_forward_ref(value)
|
| 595 |
+
|
| 596 |
+
type_hints[name] = eval_type_backport(value, globalns, localns, type_params)
|
| 597 |
+
|
| 598 |
+
return type_hints
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
# TODO use typing.ForwardRef directly when we stop supporting 3.9:
|
| 602 |
+
if sys.version_info < (3, 9, 8) or (3, 10) <= sys.version_info < (3, 10, 1):
|
| 603 |
+
|
| 604 |
+
def _make_forward_ref(
|
| 605 |
+
arg: Any,
|
| 606 |
+
is_argument: bool = True,
|
| 607 |
+
*,
|
| 608 |
+
is_class: bool = False,
|
| 609 |
+
) -> typing.ForwardRef:
|
| 610 |
+
"""Wrapper for ForwardRef that accounts for the `is_class` argument missing in older versions.
|
| 611 |
+
The `module` argument is omitted as it breaks <3.9.8, =3.10.0 and isn't used in the calls below.
|
| 612 |
+
|
| 613 |
+
See https://github.com/python/cpython/pull/28560 for some background.
|
| 614 |
+
The backport happened on 3.9.8, see:
|
| 615 |
+
https://github.com/pydantic/pydantic/discussions/6244#discussioncomment-6275458,
|
| 616 |
+
and on 3.10.1 for the 3.10 branch, see:
|
| 617 |
+
https://github.com/pydantic/pydantic/issues/6912
|
| 618 |
+
|
| 619 |
+
Implemented as EAFP with memory.
|
| 620 |
+
"""
|
| 621 |
+
return typing.ForwardRef(arg, is_argument) # pyright: ignore[reportCallIssue]
|
| 622 |
+
|
| 623 |
+
else:
|
| 624 |
+
_make_forward_ref = typing.ForwardRef # pyright: ignore[reportAssignmentType]
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
if sys.version_info >= (3, 10):
|
| 628 |
+
get_type_hints = typing.get_type_hints
|
| 629 |
+
|
| 630 |
+
else:
|
| 631 |
+
"""
|
| 632 |
+
For older versions of python, we have a custom implementation of `get_type_hints` which is a close as possible to
|
| 633 |
+
the implementation in CPython 3.10.8.
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
@typing.no_type_check
|
| 637 |
+
def get_type_hints( # noqa: C901
|
| 638 |
+
obj: Any,
|
| 639 |
+
globalns: dict[str, Any] | None = None,
|
| 640 |
+
localns: dict[str, Any] | None = None,
|
| 641 |
+
include_extras: bool = False,
|
| 642 |
+
) -> dict[str, Any]: # pragma: no cover
|
| 643 |
+
"""Taken verbatim from python 3.10.8 unchanged, except:
|
| 644 |
+
* type annotations of the function definition above.
|
| 645 |
+
* prefixing `typing.` where appropriate
|
| 646 |
+
* Use `_make_forward_ref` instead of `typing.ForwardRef` to handle the `is_class` argument.
|
| 647 |
+
|
| 648 |
+
https://github.com/python/cpython/blob/aaaf5174241496afca7ce4d4584570190ff972fe/Lib/typing.py#L1773-L1875
|
| 649 |
+
|
| 650 |
+
DO NOT CHANGE THIS METHOD UNLESS ABSOLUTELY NECESSARY.
|
| 651 |
+
======================================================
|
| 652 |
+
|
| 653 |
+
Return type hints for an object.
|
| 654 |
+
|
| 655 |
+
This is often the same as obj.__annotations__, but it handles
|
| 656 |
+
forward references encoded as string literals, adds Optional[t] if a
|
| 657 |
+
default value equal to None is set and recursively replaces all
|
| 658 |
+
'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
|
| 659 |
+
|
| 660 |
+
The argument may be a module, class, method, or function. The annotations
|
| 661 |
+
are returned as a dictionary. For classes, annotations include also
|
| 662 |
+
inherited members.
|
| 663 |
+
|
| 664 |
+
TypeError is raised if the argument is not of a type that can contain
|
| 665 |
+
annotations, and an empty dictionary is returned if no annotations are
|
| 666 |
+
present.
|
| 667 |
+
|
| 668 |
+
BEWARE -- the behavior of globalns and localns is counterintuitive
|
| 669 |
+
(unless you are familiar with how eval() and exec() work). The
|
| 670 |
+
search order is locals first, then globals.
|
| 671 |
+
|
| 672 |
+
- If no dict arguments are passed, an attempt is made to use the
|
| 673 |
+
globals from obj (or the respective module's globals for classes),
|
| 674 |
+
and these are also used as the locals. If the object does not appear
|
| 675 |
+
to have globals, an empty dictionary is used. For classes, the search
|
| 676 |
+
order is globals first then locals.
|
| 677 |
+
|
| 678 |
+
- If one dict argument is passed, it is used for both globals and
|
| 679 |
+
locals.
|
| 680 |
+
|
| 681 |
+
- If two dict arguments are passed, they specify globals and
|
| 682 |
+
locals, respectively.
|
| 683 |
+
"""
|
| 684 |
+
if getattr(obj, '__no_type_check__', None):
|
| 685 |
+
return {}
|
| 686 |
+
# Classes require a special treatment.
|
| 687 |
+
if isinstance(obj, type):
|
| 688 |
+
hints = {}
|
| 689 |
+
for base in reversed(obj.__mro__):
|
| 690 |
+
if globalns is None:
|
| 691 |
+
base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
|
| 692 |
+
else:
|
| 693 |
+
base_globals = globalns
|
| 694 |
+
ann = base.__dict__.get('__annotations__', {})
|
| 695 |
+
if isinstance(ann, types.GetSetDescriptorType):
|
| 696 |
+
ann = {}
|
| 697 |
+
base_locals = dict(vars(base)) if localns is None else localns
|
| 698 |
+
if localns is None and globalns is None:
|
| 699 |
+
# This is surprising, but required. Before Python 3.10,
|
| 700 |
+
# get_type_hints only evaluated the globalns of
|
| 701 |
+
# a class. To maintain backwards compatibility, we reverse
|
| 702 |
+
# the globalns and localns order so that eval() looks into
|
| 703 |
+
# *base_globals* first rather than *base_locals*.
|
| 704 |
+
# This only affects ForwardRefs.
|
| 705 |
+
base_globals, base_locals = base_locals, base_globals
|
| 706 |
+
for name, value in ann.items():
|
| 707 |
+
if value is None:
|
| 708 |
+
value = type(None)
|
| 709 |
+
if isinstance(value, str):
|
| 710 |
+
value = _make_forward_ref(value, is_argument=False, is_class=True)
|
| 711 |
+
|
| 712 |
+
value = eval_type_backport(value, base_globals, base_locals)
|
| 713 |
+
hints[name] = value
|
| 714 |
+
if not include_extras and hasattr(typing, '_strip_annotations'):
|
| 715 |
+
return {
|
| 716 |
+
k: typing._strip_annotations(t) # type: ignore
|
| 717 |
+
for k, t in hints.items()
|
| 718 |
+
}
|
| 719 |
+
else:
|
| 720 |
+
return hints
|
| 721 |
+
|
| 722 |
+
if globalns is None:
|
| 723 |
+
if isinstance(obj, types.ModuleType):
|
| 724 |
+
globalns = obj.__dict__
|
| 725 |
+
else:
|
| 726 |
+
nsobj = obj
|
| 727 |
+
# Find globalns for the unwrapped object.
|
| 728 |
+
while hasattr(nsobj, '__wrapped__'):
|
| 729 |
+
nsobj = nsobj.__wrapped__
|
| 730 |
+
globalns = getattr(nsobj, '__globals__', {})
|
| 731 |
+
if localns is None:
|
| 732 |
+
localns = globalns
|
| 733 |
+
elif localns is None:
|
| 734 |
+
localns = globalns
|
| 735 |
+
hints = getattr(obj, '__annotations__', None)
|
| 736 |
+
if hints is None:
|
| 737 |
+
# Return empty annotations for something that _could_ have them.
|
| 738 |
+
if isinstance(obj, typing._allowed_types): # type: ignore
|
| 739 |
+
return {}
|
| 740 |
+
else:
|
| 741 |
+
raise TypeError(f'{obj!r} is not a module, class, method, or function.')
|
| 742 |
+
defaults = typing._get_defaults(obj) # type: ignore
|
| 743 |
+
hints = dict(hints)
|
| 744 |
+
for name, value in hints.items():
|
| 745 |
+
if value is None:
|
| 746 |
+
value = type(None)
|
| 747 |
+
if isinstance(value, str):
|
| 748 |
+
# class-level forward refs were handled above, this must be either
|
| 749 |
+
# a module-level annotation or a function argument annotation
|
| 750 |
+
|
| 751 |
+
value = _make_forward_ref(
|
| 752 |
+
value,
|
| 753 |
+
is_argument=not isinstance(obj, types.ModuleType),
|
| 754 |
+
is_class=False,
|
| 755 |
+
)
|
| 756 |
+
value = eval_type_backport(value, globalns, localns)
|
| 757 |
+
if name in defaults and defaults[name] is None:
|
| 758 |
+
value = typing.Optional[value]
|
| 759 |
+
hints[name] = value
|
| 760 |
+
return hints if include_extras else {k: typing._strip_annotations(t) for k, t in hints.items()} # type: ignore
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_utils.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bucket of reusable internal utilities.
|
| 2 |
+
|
| 3 |
+
This should be reduced as much as possible with functions only used in one place, moved to that place.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations as _annotations
|
| 7 |
+
|
| 8 |
+
import dataclasses
|
| 9 |
+
import keyword
|
| 10 |
+
import sys
|
| 11 |
+
import warnings
|
| 12 |
+
import weakref
|
| 13 |
+
from collections import OrderedDict, defaultdict, deque
|
| 14 |
+
from collections.abc import Callable, Iterable, Mapping
|
| 15 |
+
from collections.abc import Set as AbstractSet
|
| 16 |
+
from copy import deepcopy
|
| 17 |
+
from functools import cached_property
|
| 18 |
+
from inspect import Parameter
|
| 19 |
+
from itertools import zip_longest
|
| 20 |
+
from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType
|
| 21 |
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
|
| 22 |
+
|
| 23 |
+
from typing_extensions import TypeAlias, TypeGuard, deprecated
|
| 24 |
+
|
| 25 |
+
from pydantic import PydanticDeprecatedSince211
|
| 26 |
+
|
| 27 |
+
from . import _repr, _typing_extra
|
| 28 |
+
from ._import_utils import import_cached_base_model
|
| 29 |
+
|
| 30 |
+
if TYPE_CHECKING:
|
| 31 |
+
# TODO remove type error comments when we drop support for Python 3.9
|
| 32 |
+
MappingIntStrAny: TypeAlias = Mapping[int, Any] | Mapping[str, Any] # pyright: ignore[reportGeneralTypeIssues]
|
| 33 |
+
AbstractSetIntStr: TypeAlias = AbstractSet[int] | AbstractSet[str] # pyright: ignore[reportGeneralTypeIssues]
|
| 34 |
+
from ..main import BaseModel
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# these are types that are returned unchanged by deepcopy
|
| 38 |
+
IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = {
|
| 39 |
+
int,
|
| 40 |
+
float,
|
| 41 |
+
complex,
|
| 42 |
+
str,
|
| 43 |
+
bool,
|
| 44 |
+
bytes,
|
| 45 |
+
type,
|
| 46 |
+
_typing_extra.NoneType,
|
| 47 |
+
FunctionType,
|
| 48 |
+
BuiltinFunctionType,
|
| 49 |
+
LambdaType,
|
| 50 |
+
weakref.ref,
|
| 51 |
+
CodeType,
|
| 52 |
+
# note: including ModuleType will differ from behaviour of deepcopy by not producing error.
|
| 53 |
+
# It might be not a good idea in general, but considering that this function used only internally
|
| 54 |
+
# against default values of fields, this will allow to actually have a field with module as default value
|
| 55 |
+
ModuleType,
|
| 56 |
+
NotImplemented.__class__,
|
| 57 |
+
Ellipsis.__class__,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
# these are types that if empty, might be copied with simple copy() instead of deepcopy()
|
| 61 |
+
BUILTIN_COLLECTIONS: set[type[Any]] = {
|
| 62 |
+
list,
|
| 63 |
+
set,
|
| 64 |
+
tuple,
|
| 65 |
+
frozenset,
|
| 66 |
+
dict,
|
| 67 |
+
OrderedDict,
|
| 68 |
+
defaultdict,
|
| 69 |
+
deque,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def can_be_positional(param: Parameter) -> bool:
|
| 74 |
+
"""Return whether the parameter accepts a positional argument.
|
| 75 |
+
|
| 76 |
+
```python {test="skip" lint="skip"}
|
| 77 |
+
def func(a, /, b, *, c):
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
params = inspect.signature(func).parameters
|
| 81 |
+
can_be_positional(params['a'])
|
| 82 |
+
#> True
|
| 83 |
+
can_be_positional(params['b'])
|
| 84 |
+
#> True
|
| 85 |
+
can_be_positional(params['c'])
|
| 86 |
+
#> False
|
| 87 |
+
```
|
| 88 |
+
"""
|
| 89 |
+
return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def sequence_like(v: Any) -> bool:
|
| 93 |
+
return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def lenient_isinstance(o: Any, class_or_tuple: type[Any] | tuple[type[Any], ...] | None) -> bool: # pragma: no cover
|
| 97 |
+
try:
|
| 98 |
+
return isinstance(o, class_or_tuple) # type: ignore[arg-type]
|
| 99 |
+
except TypeError:
|
| 100 |
+
return False
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover
|
| 104 |
+
try:
|
| 105 |
+
return isinstance(cls, type) and issubclass(cls, class_or_tuple)
|
| 106 |
+
except TypeError:
|
| 107 |
+
if isinstance(cls, _typing_extra.WithArgsTypes):
|
| 108 |
+
return False
|
| 109 |
+
raise # pragma: no cover
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]:
|
| 113 |
+
"""Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
|
| 114 |
+
unlike raw calls to lenient_issubclass.
|
| 115 |
+
"""
|
| 116 |
+
BaseModel = import_cached_base_model()
|
| 117 |
+
|
| 118 |
+
return lenient_issubclass(cls, BaseModel) and cls is not BaseModel
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def is_valid_identifier(identifier: str) -> bool:
|
| 122 |
+
"""Checks that a string is a valid identifier and not a Python keyword.
|
| 123 |
+
:param identifier: The identifier to test.
|
| 124 |
+
:return: True if the identifier is valid.
|
| 125 |
+
"""
|
| 126 |
+
return identifier.isidentifier() and not keyword.iskeyword(identifier)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
KeyType = TypeVar('KeyType')
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]:
|
| 133 |
+
updated_mapping = mapping.copy()
|
| 134 |
+
for updating_mapping in updating_mappings:
|
| 135 |
+
for k, v in updating_mapping.items():
|
| 136 |
+
if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):
|
| 137 |
+
updated_mapping[k] = deep_update(updated_mapping[k], v)
|
| 138 |
+
else:
|
| 139 |
+
updated_mapping[k] = v
|
| 140 |
+
return updated_mapping
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def update_not_none(mapping: dict[Any, Any], **update: Any) -> None:
|
| 144 |
+
mapping.update({k: v for k, v in update.items() if v is not None})
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
T = TypeVar('T')
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def unique_list(
|
| 151 |
+
input_list: list[T] | tuple[T, ...],
|
| 152 |
+
*,
|
| 153 |
+
name_factory: Callable[[T], str] = str,
|
| 154 |
+
) -> list[T]:
|
| 155 |
+
"""Make a list unique while maintaining order.
|
| 156 |
+
We update the list if another one with the same name is set
|
| 157 |
+
(e.g. model validator overridden in subclass).
|
| 158 |
+
"""
|
| 159 |
+
result: list[T] = []
|
| 160 |
+
result_names: list[str] = []
|
| 161 |
+
for v in input_list:
|
| 162 |
+
v_name = name_factory(v)
|
| 163 |
+
if v_name not in result_names:
|
| 164 |
+
result_names.append(v_name)
|
| 165 |
+
result.append(v)
|
| 166 |
+
else:
|
| 167 |
+
result[result_names.index(v_name)] = v
|
| 168 |
+
|
| 169 |
+
return result
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class ValueItems(_repr.Representation):
|
| 173 |
+
"""Class for more convenient calculation of excluded or included fields on values."""
|
| 174 |
+
|
| 175 |
+
__slots__ = ('_items', '_type')
|
| 176 |
+
|
| 177 |
+
def __init__(self, value: Any, items: AbstractSetIntStr | MappingIntStrAny) -> None:
|
| 178 |
+
items = self._coerce_items(items)
|
| 179 |
+
|
| 180 |
+
if isinstance(value, (list, tuple)):
|
| 181 |
+
items = self._normalize_indexes(items, len(value)) # type: ignore
|
| 182 |
+
|
| 183 |
+
self._items: MappingIntStrAny = items # type: ignore
|
| 184 |
+
|
| 185 |
+
def is_excluded(self, item: Any) -> bool:
|
| 186 |
+
"""Check if item is fully excluded.
|
| 187 |
+
|
| 188 |
+
:param item: key or index of a value
|
| 189 |
+
"""
|
| 190 |
+
return self.is_true(self._items.get(item))
|
| 191 |
+
|
| 192 |
+
def is_included(self, item: Any) -> bool:
|
| 193 |
+
"""Check if value is contained in self._items.
|
| 194 |
+
|
| 195 |
+
:param item: key or index of value
|
| 196 |
+
"""
|
| 197 |
+
return item in self._items
|
| 198 |
+
|
| 199 |
+
def for_element(self, e: int | str) -> AbstractSetIntStr | MappingIntStrAny | None:
|
| 200 |
+
""":param e: key or index of element on value
|
| 201 |
+
:return: raw values for element if self._items is dict and contain needed element
|
| 202 |
+
"""
|
| 203 |
+
item = self._items.get(e) # type: ignore
|
| 204 |
+
return item if not self.is_true(item) else None
|
| 205 |
+
|
| 206 |
+
def _normalize_indexes(self, items: MappingIntStrAny, v_length: int) -> dict[int | str, Any]:
|
| 207 |
+
""":param items: dict or set of indexes which will be normalized
|
| 208 |
+
:param v_length: length of sequence indexes of which will be
|
| 209 |
+
|
| 210 |
+
>>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
|
| 211 |
+
{0: True, 2: True, 3: True}
|
| 212 |
+
>>> self._normalize_indexes({'__all__': True}, 4)
|
| 213 |
+
{0: True, 1: True, 2: True, 3: True}
|
| 214 |
+
"""
|
| 215 |
+
normalized_items: dict[int | str, Any] = {}
|
| 216 |
+
all_items = None
|
| 217 |
+
for i, v in items.items():
|
| 218 |
+
if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)):
|
| 219 |
+
raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}')
|
| 220 |
+
if i == '__all__':
|
| 221 |
+
all_items = self._coerce_value(v)
|
| 222 |
+
continue
|
| 223 |
+
if not isinstance(i, int):
|
| 224 |
+
raise TypeError(
|
| 225 |
+
'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: '
|
| 226 |
+
'expected integer keys or keyword "__all__"'
|
| 227 |
+
)
|
| 228 |
+
normalized_i = v_length + i if i < 0 else i
|
| 229 |
+
normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i))
|
| 230 |
+
|
| 231 |
+
if not all_items:
|
| 232 |
+
return normalized_items
|
| 233 |
+
if self.is_true(all_items):
|
| 234 |
+
for i in range(v_length):
|
| 235 |
+
normalized_items.setdefault(i, ...)
|
| 236 |
+
return normalized_items
|
| 237 |
+
for i in range(v_length):
|
| 238 |
+
normalized_item = normalized_items.setdefault(i, {})
|
| 239 |
+
if not self.is_true(normalized_item):
|
| 240 |
+
normalized_items[i] = self.merge(all_items, normalized_item)
|
| 241 |
+
return normalized_items
|
| 242 |
+
|
| 243 |
+
@classmethod
|
| 244 |
+
def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any:
|
| 245 |
+
"""Merge a `base` item with an `override` item.
|
| 246 |
+
|
| 247 |
+
Both `base` and `override` are converted to dictionaries if possible.
|
| 248 |
+
Sets are converted to dictionaries with the sets entries as keys and
|
| 249 |
+
Ellipsis as values.
|
| 250 |
+
|
| 251 |
+
Each key-value pair existing in `base` is merged with `override`,
|
| 252 |
+
while the rest of the key-value pairs are updated recursively with this function.
|
| 253 |
+
|
| 254 |
+
Merging takes place based on the "union" of keys if `intersect` is
|
| 255 |
+
set to `False` (default) and on the intersection of keys if
|
| 256 |
+
`intersect` is set to `True`.
|
| 257 |
+
"""
|
| 258 |
+
override = cls._coerce_value(override)
|
| 259 |
+
base = cls._coerce_value(base)
|
| 260 |
+
if override is None:
|
| 261 |
+
return base
|
| 262 |
+
if cls.is_true(base) or base is None:
|
| 263 |
+
return override
|
| 264 |
+
if cls.is_true(override):
|
| 265 |
+
return base if intersect else override
|
| 266 |
+
|
| 267 |
+
# intersection or union of keys while preserving ordering:
|
| 268 |
+
if intersect:
|
| 269 |
+
merge_keys = [k for k in base if k in override] + [k for k in override if k in base]
|
| 270 |
+
else:
|
| 271 |
+
merge_keys = list(base) + [k for k in override if k not in base]
|
| 272 |
+
|
| 273 |
+
merged: dict[int | str, Any] = {}
|
| 274 |
+
for k in merge_keys:
|
| 275 |
+
merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
|
| 276 |
+
if merged_item is not None:
|
| 277 |
+
merged[k] = merged_item
|
| 278 |
+
|
| 279 |
+
return merged
|
| 280 |
+
|
| 281 |
+
@staticmethod
|
| 282 |
+
def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny:
|
| 283 |
+
if isinstance(items, Mapping):
|
| 284 |
+
pass
|
| 285 |
+
elif isinstance(items, AbstractSet):
|
| 286 |
+
items = dict.fromkeys(items, ...) # type: ignore
|
| 287 |
+
else:
|
| 288 |
+
class_name = getattr(items, '__class__', '???')
|
| 289 |
+
raise TypeError(f'Unexpected type of exclude value {class_name}')
|
| 290 |
+
return items # type: ignore
|
| 291 |
+
|
| 292 |
+
@classmethod
|
| 293 |
+
def _coerce_value(cls, value: Any) -> Any:
|
| 294 |
+
if value is None or cls.is_true(value):
|
| 295 |
+
return value
|
| 296 |
+
return cls._coerce_items(value)
|
| 297 |
+
|
| 298 |
+
@staticmethod
|
| 299 |
+
def is_true(v: Any) -> bool:
|
| 300 |
+
return v is True or v is ...
|
| 301 |
+
|
| 302 |
+
def __repr_args__(self) -> _repr.ReprArgs:
|
| 303 |
+
return [(None, self._items)]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if TYPE_CHECKING:
|
| 307 |
+
|
| 308 |
+
def LazyClassAttribute(name: str, get_value: Callable[[], T]) -> T: ...
|
| 309 |
+
|
| 310 |
+
else:
|
| 311 |
+
|
| 312 |
+
class LazyClassAttribute:
|
| 313 |
+
"""A descriptor exposing an attribute only accessible on a class (hidden from instances).
|
| 314 |
+
|
| 315 |
+
The attribute is lazily computed and cached during the first access.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, name: str, get_value: Callable[[], Any]) -> None:
|
| 319 |
+
self.name = name
|
| 320 |
+
self.get_value = get_value
|
| 321 |
+
|
| 322 |
+
@cached_property
|
| 323 |
+
def value(self) -> Any:
|
| 324 |
+
return self.get_value()
|
| 325 |
+
|
| 326 |
+
def __get__(self, instance: Any, owner: type[Any]) -> None:
|
| 327 |
+
if instance is None:
|
| 328 |
+
return self.value
|
| 329 |
+
raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
Obj = TypeVar('Obj')
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def smart_deepcopy(obj: Obj) -> Obj:
|
| 336 |
+
"""Return type as is for immutable built-in types
|
| 337 |
+
Use obj.copy() for built-in empty collections
|
| 338 |
+
Use copy.deepcopy() for non-empty collections and unknown objects.
|
| 339 |
+
"""
|
| 340 |
+
obj_type = obj.__class__
|
| 341 |
+
if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
|
| 342 |
+
return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
|
| 343 |
+
try:
|
| 344 |
+
if not obj and obj_type in BUILTIN_COLLECTIONS:
|
| 345 |
+
# faster way for empty collections, no need to copy its members
|
| 346 |
+
return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore
|
| 347 |
+
except (TypeError, ValueError, RuntimeError):
|
| 348 |
+
# do we really dare to catch ALL errors? Seems a bit risky
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
return deepcopy(obj) # slowest way when we actually might need a deepcopy
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
_SENTINEL = object()
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
|
| 358 |
+
"""Check that the items of `left` are the same objects as those in `right`.
|
| 359 |
+
|
| 360 |
+
>>> a, b = object(), object()
|
| 361 |
+
>>> all_identical([a, b, a], [a, b, a])
|
| 362 |
+
True
|
| 363 |
+
>>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical"
|
| 364 |
+
False
|
| 365 |
+
"""
|
| 366 |
+
for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL):
|
| 367 |
+
if left_item is not right_item:
|
| 368 |
+
return False
|
| 369 |
+
return True
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def get_first_not_none(a: Any, b: Any) -> Any:
|
| 373 |
+
"""Return the first argument if it is not `None`, otherwise return the second argument."""
|
| 374 |
+
return a if a is not None else b
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@dataclasses.dataclass(frozen=True)
|
| 378 |
+
class SafeGetItemProxy:
|
| 379 |
+
"""Wrapper redirecting `__getitem__` to `get` with a sentinel value as default
|
| 380 |
+
|
| 381 |
+
This makes is safe to use in `operator.itemgetter` when some keys may be missing
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
# Define __slots__manually for performances
|
| 385 |
+
# @dataclasses.dataclass() only support slots=True in python>=3.10
|
| 386 |
+
__slots__ = ('wrapped',)
|
| 387 |
+
|
| 388 |
+
wrapped: Mapping[str, Any]
|
| 389 |
+
|
| 390 |
+
def __getitem__(self, key: str, /) -> Any:
|
| 391 |
+
return self.wrapped.get(key, _SENTINEL)
|
| 392 |
+
|
| 393 |
+
# required to pass the object to operator.itemgetter() instances due to a quirk of typeshed
|
| 394 |
+
# https://github.com/python/mypy/issues/13713
|
| 395 |
+
# https://github.com/python/typeshed/pull/8785
|
| 396 |
+
# Since this is typing-only, hide it in a typing.TYPE_CHECKING block
|
| 397 |
+
if TYPE_CHECKING:
|
| 398 |
+
|
| 399 |
+
def __contains__(self, key: str, /) -> bool:
|
| 400 |
+
return self.wrapped.__contains__(key)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
_ModelT = TypeVar('_ModelT', bound='BaseModel')
|
| 404 |
+
_RT = TypeVar('_RT')
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class deprecated_instance_property(Generic[_ModelT, _RT]):
|
| 408 |
+
"""A decorator exposing the decorated class method as a property, with a warning on instance access.
|
| 409 |
+
|
| 410 |
+
This decorator takes a class method defined on the `BaseModel` class and transforms it into
|
| 411 |
+
an attribute. The attribute can be accessed on both the class and instances of the class. If accessed
|
| 412 |
+
via an instance, a deprecation warning is emitted stating that instance access will be removed in V3.
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
def __init__(self, fget: Callable[[type[_ModelT]], _RT], /) -> None:
|
| 416 |
+
# Note: fget should be a classmethod:
|
| 417 |
+
self.fget = fget
|
| 418 |
+
|
| 419 |
+
@overload
|
| 420 |
+
def __get__(self, instance: None, objtype: type[_ModelT]) -> _RT: ...
|
| 421 |
+
@overload
|
| 422 |
+
@deprecated(
|
| 423 |
+
'Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3. '
|
| 424 |
+
'Instead, you should access this attribute from the model class.',
|
| 425 |
+
category=None,
|
| 426 |
+
)
|
| 427 |
+
def __get__(self, instance: _ModelT, objtype: type[_ModelT]) -> _RT: ...
|
| 428 |
+
def __get__(self, instance: _ModelT | None, objtype: type[_ModelT]) -> _RT:
|
| 429 |
+
if instance is not None:
|
| 430 |
+
# fmt: off
|
| 431 |
+
attr_name = (
|
| 432 |
+
self.fget.__name__
|
| 433 |
+
if sys.version_info >= (3, 10)
|
| 434 |
+
else self.fget.__func__.__name__ # pyright: ignore[reportFunctionMemberAccess]
|
| 435 |
+
)
|
| 436 |
+
# fmt: on
|
| 437 |
+
warnings.warn(
|
| 438 |
+
f'Accessing the {attr_name!r} attribute on the instance is deprecated. '
|
| 439 |
+
'Instead, you should access this attribute from the model class.',
|
| 440 |
+
category=PydanticDeprecatedSince211,
|
| 441 |
+
stacklevel=2,
|
| 442 |
+
)
|
| 443 |
+
return self.fget.__get__(instance, objtype)()
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_validate_call.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import inspect
|
| 5 |
+
from collections.abc import Awaitable
|
| 6 |
+
from functools import partial
|
| 7 |
+
from typing import Any, Callable
|
| 8 |
+
|
| 9 |
+
import pydantic_core
|
| 10 |
+
|
| 11 |
+
from ..config import ConfigDict
|
| 12 |
+
from ..plugin._schema_validator import create_schema_validator
|
| 13 |
+
from ._config import ConfigWrapper
|
| 14 |
+
from ._generate_schema import GenerateSchema, ValidateCallSupportedTypes
|
| 15 |
+
from ._namespace_utils import MappingNamespace, NsResolver, ns_for_function
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def extract_function_name(func: ValidateCallSupportedTypes) -> str:
|
| 19 |
+
"""Extract the name of a `ValidateCallSupportedTypes` object."""
|
| 20 |
+
return f'partial({func.func.__name__})' if isinstance(func, functools.partial) else func.__name__
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def extract_function_qualname(func: ValidateCallSupportedTypes) -> str:
|
| 24 |
+
"""Extract the qualname of a `ValidateCallSupportedTypes` object."""
|
| 25 |
+
return f'partial({func.func.__qualname__})' if isinstance(func, functools.partial) else func.__qualname__
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def update_wrapper_attributes(wrapped: ValidateCallSupportedTypes, wrapper: Callable[..., Any]):
|
| 29 |
+
"""Update the `wrapper` function with the attributes of the `wrapped` function. Return the updated function."""
|
| 30 |
+
if inspect.iscoroutinefunction(wrapped):
|
| 31 |
+
|
| 32 |
+
@functools.wraps(wrapped)
|
| 33 |
+
async def wrapper_function(*args, **kwargs): # type: ignore
|
| 34 |
+
return await wrapper(*args, **kwargs)
|
| 35 |
+
else:
|
| 36 |
+
|
| 37 |
+
@functools.wraps(wrapped)
|
| 38 |
+
def wrapper_function(*args, **kwargs):
|
| 39 |
+
return wrapper(*args, **kwargs)
|
| 40 |
+
|
| 41 |
+
# We need to manually update this because `partial` object has no `__name__` and `__qualname__`.
|
| 42 |
+
wrapper_function.__name__ = extract_function_name(wrapped)
|
| 43 |
+
wrapper_function.__qualname__ = extract_function_qualname(wrapped)
|
| 44 |
+
wrapper_function.raw_function = wrapped # type: ignore
|
| 45 |
+
|
| 46 |
+
return wrapper_function
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ValidateCallWrapper:
|
| 50 |
+
"""This is a wrapper around a function that validates the arguments passed to it, and optionally the return value."""
|
| 51 |
+
|
| 52 |
+
__slots__ = (
|
| 53 |
+
'function',
|
| 54 |
+
'validate_return',
|
| 55 |
+
'schema_type',
|
| 56 |
+
'module',
|
| 57 |
+
'qualname',
|
| 58 |
+
'ns_resolver',
|
| 59 |
+
'config_wrapper',
|
| 60 |
+
'__pydantic_complete__',
|
| 61 |
+
'__pydantic_validator__',
|
| 62 |
+
'__return_pydantic_validator__',
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
function: ValidateCallSupportedTypes,
|
| 68 |
+
config: ConfigDict | None,
|
| 69 |
+
validate_return: bool,
|
| 70 |
+
parent_namespace: MappingNamespace | None,
|
| 71 |
+
) -> None:
|
| 72 |
+
self.function = function
|
| 73 |
+
self.validate_return = validate_return
|
| 74 |
+
if isinstance(function, partial):
|
| 75 |
+
self.schema_type = function.func
|
| 76 |
+
self.module = function.func.__module__
|
| 77 |
+
else:
|
| 78 |
+
self.schema_type = function
|
| 79 |
+
self.module = function.__module__
|
| 80 |
+
self.qualname = extract_function_qualname(function)
|
| 81 |
+
|
| 82 |
+
self.ns_resolver = NsResolver(
|
| 83 |
+
namespaces_tuple=ns_for_function(self.schema_type, parent_namespace=parent_namespace)
|
| 84 |
+
)
|
| 85 |
+
self.config_wrapper = ConfigWrapper(config)
|
| 86 |
+
if not self.config_wrapper.defer_build:
|
| 87 |
+
self._create_validators()
|
| 88 |
+
else:
|
| 89 |
+
self.__pydantic_complete__ = False
|
| 90 |
+
|
| 91 |
+
def _create_validators(self) -> None:
|
| 92 |
+
gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
|
| 93 |
+
schema = gen_schema.clean_schema(gen_schema.generate_schema(self.function))
|
| 94 |
+
core_config = self.config_wrapper.core_config(title=self.qualname)
|
| 95 |
+
|
| 96 |
+
self.__pydantic_validator__ = create_schema_validator(
|
| 97 |
+
schema,
|
| 98 |
+
self.schema_type,
|
| 99 |
+
self.module,
|
| 100 |
+
self.qualname,
|
| 101 |
+
'validate_call',
|
| 102 |
+
core_config,
|
| 103 |
+
self.config_wrapper.plugin_settings,
|
| 104 |
+
)
|
| 105 |
+
if self.validate_return:
|
| 106 |
+
signature = inspect.signature(self.function)
|
| 107 |
+
return_type = signature.return_annotation if signature.return_annotation is not signature.empty else Any
|
| 108 |
+
gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
|
| 109 |
+
schema = gen_schema.clean_schema(gen_schema.generate_schema(return_type))
|
| 110 |
+
validator = create_schema_validator(
|
| 111 |
+
schema,
|
| 112 |
+
self.schema_type,
|
| 113 |
+
self.module,
|
| 114 |
+
self.qualname,
|
| 115 |
+
'validate_call',
|
| 116 |
+
core_config,
|
| 117 |
+
self.config_wrapper.plugin_settings,
|
| 118 |
+
)
|
| 119 |
+
if inspect.iscoroutinefunction(self.function):
|
| 120 |
+
|
| 121 |
+
async def return_val_wrapper(aw: Awaitable[Any]) -> None:
|
| 122 |
+
return validator.validate_python(await aw)
|
| 123 |
+
|
| 124 |
+
self.__return_pydantic_validator__ = return_val_wrapper
|
| 125 |
+
else:
|
| 126 |
+
self.__return_pydantic_validator__ = validator.validate_python
|
| 127 |
+
else:
|
| 128 |
+
self.__return_pydantic_validator__ = None
|
| 129 |
+
|
| 130 |
+
self.__pydantic_complete__ = True
|
| 131 |
+
|
| 132 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 133 |
+
if not self.__pydantic_complete__:
|
| 134 |
+
self._create_validators()
|
| 135 |
+
|
| 136 |
+
res = self.__pydantic_validator__.validate_python(pydantic_core.ArgsKwargs(args, kwargs))
|
| 137 |
+
if self.__return_pydantic_validator__:
|
| 138 |
+
return self.__return_pydantic_validator__(res)
|
| 139 |
+
else:
|
| 140 |
+
return res
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/_internal/_validators.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validator functions for standard library types.
|
| 2 |
+
|
| 3 |
+
Import of this module is deferred since it contains imports of many standard library modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations as _annotations
|
| 7 |
+
|
| 8 |
+
import collections.abc
|
| 9 |
+
import math
|
| 10 |
+
import re
|
| 11 |
+
import typing
|
| 12 |
+
from collections.abc import Sequence
|
| 13 |
+
from decimal import Decimal
|
| 14 |
+
from fractions import Fraction
|
| 15 |
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
| 16 |
+
from typing import Any, Callable, TypeVar, Union, cast
|
| 17 |
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
| 18 |
+
|
| 19 |
+
import typing_extensions
|
| 20 |
+
from pydantic_core import PydanticCustomError, PydanticKnownError, core_schema
|
| 21 |
+
from typing_extensions import get_args, get_origin
|
| 22 |
+
from typing_inspection import typing_objects
|
| 23 |
+
|
| 24 |
+
from pydantic._internal._import_utils import import_cached_field_info
|
| 25 |
+
from pydantic.errors import PydanticSchemaGenerationError
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def sequence_validator(
|
| 29 |
+
input_value: Sequence[Any],
|
| 30 |
+
/,
|
| 31 |
+
validator: core_schema.ValidatorFunctionWrapHandler,
|
| 32 |
+
) -> Sequence[Any]:
|
| 33 |
+
"""Validator for `Sequence` types, isinstance(v, Sequence) has already been called."""
|
| 34 |
+
value_type = type(input_value)
|
| 35 |
+
|
| 36 |
+
# We don't accept any plain string as a sequence
|
| 37 |
+
# Relevant issue: https://github.com/pydantic/pydantic/issues/5595
|
| 38 |
+
if issubclass(value_type, (str, bytes)):
|
| 39 |
+
raise PydanticCustomError(
|
| 40 |
+
'sequence_str',
|
| 41 |
+
"'{type_name}' instances are not allowed as a Sequence value",
|
| 42 |
+
{'type_name': value_type.__name__},
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# TODO: refactor sequence validation to validate with either a list or a tuple
|
| 46 |
+
# schema, depending on the type of the value.
|
| 47 |
+
# Additionally, we should be able to remove one of either this validator or the
|
| 48 |
+
# SequenceValidator in _std_types_schema.py (preferably this one, while porting over some logic).
|
| 49 |
+
# Effectively, a refactor for sequence validation is needed.
|
| 50 |
+
if value_type is tuple:
|
| 51 |
+
input_value = list(input_value)
|
| 52 |
+
|
| 53 |
+
v_list = validator(input_value)
|
| 54 |
+
|
| 55 |
+
# the rest of the logic is just re-creating the original type from `v_list`
|
| 56 |
+
if value_type is list:
|
| 57 |
+
return v_list
|
| 58 |
+
elif issubclass(value_type, range):
|
| 59 |
+
# return the list as we probably can't re-create the range
|
| 60 |
+
return v_list
|
| 61 |
+
elif value_type is tuple:
|
| 62 |
+
return tuple(v_list)
|
| 63 |
+
else:
|
| 64 |
+
# best guess at how to re-create the original type, more custom construction logic might be required
|
| 65 |
+
return value_type(v_list) # type: ignore[call-arg]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def import_string(value: Any) -> Any:
|
| 69 |
+
if isinstance(value, str):
|
| 70 |
+
try:
|
| 71 |
+
return _import_string_logic(value)
|
| 72 |
+
except ImportError as e:
|
| 73 |
+
raise PydanticCustomError('import_error', 'Invalid python path: {error}', {'error': str(e)}) from e
|
| 74 |
+
else:
|
| 75 |
+
# otherwise we just return the value and let the next validator do the rest of the work
|
| 76 |
+
return value
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _import_string_logic(dotted_path: str) -> Any:
|
| 80 |
+
"""Inspired by uvicorn — dotted paths should include a colon before the final item if that item is not a module.
|
| 81 |
+
(This is necessary to distinguish between a submodule and an attribute when there is a conflict.).
|
| 82 |
+
|
| 83 |
+
If the dotted path does not include a colon and the final item is not a valid module, importing as an attribute
|
| 84 |
+
rather than a submodule will be attempted automatically.
|
| 85 |
+
|
| 86 |
+
So, for example, the following values of `dotted_path` result in the following returned values:
|
| 87 |
+
* 'collections': <module 'collections'>
|
| 88 |
+
* 'collections.abc': <module 'collections.abc'>
|
| 89 |
+
* 'collections.abc:Mapping': <class 'collections.abc.Mapping'>
|
| 90 |
+
* `collections.abc.Mapping`: <class 'collections.abc.Mapping'> (though this is a bit slower than the previous line)
|
| 91 |
+
|
| 92 |
+
An error will be raised under any of the following scenarios:
|
| 93 |
+
* `dotted_path` contains more than one colon (e.g., 'collections:abc:Mapping')
|
| 94 |
+
* the substring of `dotted_path` before the colon is not a valid module in the environment (e.g., '123:Mapping')
|
| 95 |
+
* the substring of `dotted_path` after the colon is not an attribute of the module (e.g., 'collections:abc123')
|
| 96 |
+
"""
|
| 97 |
+
from importlib import import_module
|
| 98 |
+
|
| 99 |
+
components = dotted_path.strip().split(':')
|
| 100 |
+
if len(components) > 2:
|
| 101 |
+
raise ImportError(f"Import strings should have at most one ':'; received {dotted_path!r}")
|
| 102 |
+
|
| 103 |
+
module_path = components[0]
|
| 104 |
+
if not module_path:
|
| 105 |
+
raise ImportError(f'Import strings should have a nonempty module name; received {dotted_path!r}')
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
module = import_module(module_path)
|
| 109 |
+
except ModuleNotFoundError as e:
|
| 110 |
+
if '.' in module_path:
|
| 111 |
+
# Check if it would be valid if the final item was separated from its module with a `:`
|
| 112 |
+
maybe_module_path, maybe_attribute = dotted_path.strip().rsplit('.', 1)
|
| 113 |
+
try:
|
| 114 |
+
return _import_string_logic(f'{maybe_module_path}:{maybe_attribute}')
|
| 115 |
+
except ImportError:
|
| 116 |
+
pass
|
| 117 |
+
raise ImportError(f'No module named {module_path!r}') from e
|
| 118 |
+
raise e
|
| 119 |
+
|
| 120 |
+
if len(components) > 1:
|
| 121 |
+
attribute = components[1]
|
| 122 |
+
try:
|
| 123 |
+
return getattr(module, attribute)
|
| 124 |
+
except AttributeError as e:
|
| 125 |
+
raise ImportError(f'cannot import name {attribute!r} from {module_path!r}') from e
|
| 126 |
+
else:
|
| 127 |
+
return module
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def pattern_either_validator(input_value: Any, /) -> re.Pattern[Any]:
|
| 131 |
+
if isinstance(input_value, re.Pattern):
|
| 132 |
+
return input_value
|
| 133 |
+
elif isinstance(input_value, (str, bytes)):
|
| 134 |
+
# todo strict mode
|
| 135 |
+
return compile_pattern(input_value) # type: ignore
|
| 136 |
+
else:
|
| 137 |
+
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def pattern_str_validator(input_value: Any, /) -> re.Pattern[str]:
|
| 141 |
+
if isinstance(input_value, re.Pattern):
|
| 142 |
+
if isinstance(input_value.pattern, str):
|
| 143 |
+
return input_value
|
| 144 |
+
else:
|
| 145 |
+
raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
|
| 146 |
+
elif isinstance(input_value, str):
|
| 147 |
+
return compile_pattern(input_value)
|
| 148 |
+
elif isinstance(input_value, bytes):
|
| 149 |
+
raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
|
| 150 |
+
else:
|
| 151 |
+
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def pattern_bytes_validator(input_value: Any, /) -> re.Pattern[bytes]:
|
| 155 |
+
if isinstance(input_value, re.Pattern):
|
| 156 |
+
if isinstance(input_value.pattern, bytes):
|
| 157 |
+
return input_value
|
| 158 |
+
else:
|
| 159 |
+
raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
|
| 160 |
+
elif isinstance(input_value, bytes):
|
| 161 |
+
return compile_pattern(input_value)
|
| 162 |
+
elif isinstance(input_value, str):
|
| 163 |
+
raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
|
| 164 |
+
else:
|
| 165 |
+
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
PatternType = TypeVar('PatternType', str, bytes)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def compile_pattern(pattern: PatternType) -> re.Pattern[PatternType]:
|
| 172 |
+
try:
|
| 173 |
+
return re.compile(pattern)
|
| 174 |
+
except re.error:
|
| 175 |
+
raise PydanticCustomError('pattern_regex', 'Input should be a valid regular expression')
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def ip_v4_address_validator(input_value: Any, /) -> IPv4Address:
|
| 179 |
+
if isinstance(input_value, IPv4Address):
|
| 180 |
+
return input_value
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
return IPv4Address(input_value)
|
| 184 |
+
except ValueError:
|
| 185 |
+
raise PydanticCustomError('ip_v4_address', 'Input is not a valid IPv4 address')
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def ip_v6_address_validator(input_value: Any, /) -> IPv6Address:
|
| 189 |
+
if isinstance(input_value, IPv6Address):
|
| 190 |
+
return input_value
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
return IPv6Address(input_value)
|
| 194 |
+
except ValueError:
|
| 195 |
+
raise PydanticCustomError('ip_v6_address', 'Input is not a valid IPv6 address')
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def ip_v4_network_validator(input_value: Any, /) -> IPv4Network:
|
| 199 |
+
"""Assume IPv4Network initialised with a default `strict` argument.
|
| 200 |
+
|
| 201 |
+
See more:
|
| 202 |
+
https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network
|
| 203 |
+
"""
|
| 204 |
+
if isinstance(input_value, IPv4Network):
|
| 205 |
+
return input_value
|
| 206 |
+
|
| 207 |
+
try:
|
| 208 |
+
return IPv4Network(input_value)
|
| 209 |
+
except ValueError:
|
| 210 |
+
raise PydanticCustomError('ip_v4_network', 'Input is not a valid IPv4 network')
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def ip_v6_network_validator(input_value: Any, /) -> IPv6Network:
|
| 214 |
+
"""Assume IPv6Network initialised with a default `strict` argument.
|
| 215 |
+
|
| 216 |
+
See more:
|
| 217 |
+
https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
|
| 218 |
+
"""
|
| 219 |
+
if isinstance(input_value, IPv6Network):
|
| 220 |
+
return input_value
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
return IPv6Network(input_value)
|
| 224 |
+
except ValueError:
|
| 225 |
+
raise PydanticCustomError('ip_v6_network', 'Input is not a valid IPv6 network')
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def ip_v4_interface_validator(input_value: Any, /) -> IPv4Interface:
|
| 229 |
+
if isinstance(input_value, IPv4Interface):
|
| 230 |
+
return input_value
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
return IPv4Interface(input_value)
|
| 234 |
+
except ValueError:
|
| 235 |
+
raise PydanticCustomError('ip_v4_interface', 'Input is not a valid IPv4 interface')
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def ip_v6_interface_validator(input_value: Any, /) -> IPv6Interface:
|
| 239 |
+
if isinstance(input_value, IPv6Interface):
|
| 240 |
+
return input_value
|
| 241 |
+
|
| 242 |
+
try:
|
| 243 |
+
return IPv6Interface(input_value)
|
| 244 |
+
except ValueError:
|
| 245 |
+
raise PydanticCustomError('ip_v6_interface', 'Input is not a valid IPv6 interface')
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def fraction_validator(input_value: Any, /) -> Fraction:
|
| 249 |
+
if isinstance(input_value, Fraction):
|
| 250 |
+
return input_value
|
| 251 |
+
|
| 252 |
+
try:
|
| 253 |
+
return Fraction(input_value)
|
| 254 |
+
except ValueError:
|
| 255 |
+
raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction')
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def forbid_inf_nan_check(x: Any) -> Any:
|
| 259 |
+
if not math.isfinite(x):
|
| 260 |
+
raise PydanticKnownError('finite_number')
|
| 261 |
+
return x
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _safe_repr(v: Any) -> int | float | str:
|
| 265 |
+
"""The context argument for `PydanticKnownError` requires a number or str type, so we do a simple repr() coercion for types like timedelta.
|
| 266 |
+
|
| 267 |
+
See tests/test_types.py::test_annotated_metadata_any_order for some context.
|
| 268 |
+
"""
|
| 269 |
+
if isinstance(v, (int, float, str)):
|
| 270 |
+
return v
|
| 271 |
+
return repr(v)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def greater_than_validator(x: Any, gt: Any) -> Any:
|
| 275 |
+
try:
|
| 276 |
+
if not (x > gt):
|
| 277 |
+
raise PydanticKnownError('greater_than', {'gt': _safe_repr(gt)})
|
| 278 |
+
return x
|
| 279 |
+
except TypeError:
|
| 280 |
+
raise TypeError(f"Unable to apply constraint 'gt' to supplied value {x}")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def greater_than_or_equal_validator(x: Any, ge: Any) -> Any:
|
| 284 |
+
try:
|
| 285 |
+
if not (x >= ge):
|
| 286 |
+
raise PydanticKnownError('greater_than_equal', {'ge': _safe_repr(ge)})
|
| 287 |
+
return x
|
| 288 |
+
except TypeError:
|
| 289 |
+
raise TypeError(f"Unable to apply constraint 'ge' to supplied value {x}")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def less_than_validator(x: Any, lt: Any) -> Any:
|
| 293 |
+
try:
|
| 294 |
+
if not (x < lt):
|
| 295 |
+
raise PydanticKnownError('less_than', {'lt': _safe_repr(lt)})
|
| 296 |
+
return x
|
| 297 |
+
except TypeError:
|
| 298 |
+
raise TypeError(f"Unable to apply constraint 'lt' to supplied value {x}")
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def less_than_or_equal_validator(x: Any, le: Any) -> Any:
|
| 302 |
+
try:
|
| 303 |
+
if not (x <= le):
|
| 304 |
+
raise PydanticKnownError('less_than_equal', {'le': _safe_repr(le)})
|
| 305 |
+
return x
|
| 306 |
+
except TypeError:
|
| 307 |
+
raise TypeError(f"Unable to apply constraint 'le' to supplied value {x}")
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def multiple_of_validator(x: Any, multiple_of: Any) -> Any:
|
| 311 |
+
try:
|
| 312 |
+
if x % multiple_of:
|
| 313 |
+
raise PydanticKnownError('multiple_of', {'multiple_of': _safe_repr(multiple_of)})
|
| 314 |
+
return x
|
| 315 |
+
except TypeError:
|
| 316 |
+
raise TypeError(f"Unable to apply constraint 'multiple_of' to supplied value {x}")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def min_length_validator(x: Any, min_length: Any) -> Any:
|
| 320 |
+
try:
|
| 321 |
+
if not (len(x) >= min_length):
|
| 322 |
+
raise PydanticKnownError(
|
| 323 |
+
'too_short', {'field_type': 'Value', 'min_length': min_length, 'actual_length': len(x)}
|
| 324 |
+
)
|
| 325 |
+
return x
|
| 326 |
+
except TypeError:
|
| 327 |
+
raise TypeError(f"Unable to apply constraint 'min_length' to supplied value {x}")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def max_length_validator(x: Any, max_length: Any) -> Any:
|
| 331 |
+
try:
|
| 332 |
+
if len(x) > max_length:
|
| 333 |
+
raise PydanticKnownError(
|
| 334 |
+
'too_long',
|
| 335 |
+
{'field_type': 'Value', 'max_length': max_length, 'actual_length': len(x)},
|
| 336 |
+
)
|
| 337 |
+
return x
|
| 338 |
+
except TypeError:
|
| 339 |
+
raise TypeError(f"Unable to apply constraint 'max_length' to supplied value {x}")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _extract_decimal_digits_info(decimal: Decimal) -> tuple[int, int]:
|
| 343 |
+
"""Compute the total number of digits and decimal places for a given [`Decimal`][decimal.Decimal] instance.
|
| 344 |
+
|
| 345 |
+
This function handles both normalized and non-normalized Decimal instances.
|
| 346 |
+
Example: Decimal('1.230') -> 4 digits, 3 decimal places
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
decimal (Decimal): The decimal number to analyze.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
tuple[int, int]: A tuple containing the number of decimal places and total digits.
|
| 353 |
+
|
| 354 |
+
Though this could be divided into two separate functions, the logic is easier to follow if we couple the computation
|
| 355 |
+
of the number of decimals and digits together.
|
| 356 |
+
"""
|
| 357 |
+
try:
|
| 358 |
+
decimal_tuple = decimal.as_tuple()
|
| 359 |
+
|
| 360 |
+
assert isinstance(decimal_tuple.exponent, int)
|
| 361 |
+
|
| 362 |
+
exponent = decimal_tuple.exponent
|
| 363 |
+
num_digits = len(decimal_tuple.digits)
|
| 364 |
+
|
| 365 |
+
if exponent >= 0:
|
| 366 |
+
# A positive exponent adds that many trailing zeros
|
| 367 |
+
# Ex: digit_tuple=(1, 2, 3), exponent=2 -> 12300 -> 0 decimal places, 5 digits
|
| 368 |
+
num_digits += exponent
|
| 369 |
+
decimal_places = 0
|
| 370 |
+
else:
|
| 371 |
+
# If the absolute value of the negative exponent is larger than the
|
| 372 |
+
# number of digits, then it's the same as the number of digits,
|
| 373 |
+
# because it'll consume all the digits in digit_tuple and then
|
| 374 |
+
# add abs(exponent) - len(digit_tuple) leading zeros after the decimal point.
|
| 375 |
+
# Ex: digit_tuple=(1, 2, 3), exponent=-2 -> 1.23 -> 2 decimal places, 3 digits
|
| 376 |
+
# Ex: digit_tuple=(1, 2, 3), exponent=-4 -> 0.0123 -> 4 decimal places, 4 digits
|
| 377 |
+
decimal_places = abs(exponent)
|
| 378 |
+
num_digits = max(num_digits, decimal_places)
|
| 379 |
+
|
| 380 |
+
return decimal_places, num_digits
|
| 381 |
+
except (AssertionError, AttributeError):
|
| 382 |
+
raise TypeError(f'Unable to extract decimal digits info from supplied value {decimal}')
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def max_digits_validator(x: Any, max_digits: Any) -> Any:
|
| 386 |
+
try:
|
| 387 |
+
_, num_digits = _extract_decimal_digits_info(x)
|
| 388 |
+
_, normalized_num_digits = _extract_decimal_digits_info(x.normalize())
|
| 389 |
+
if (num_digits > max_digits) and (normalized_num_digits > max_digits):
|
| 390 |
+
raise PydanticKnownError(
|
| 391 |
+
'decimal_max_digits',
|
| 392 |
+
{'max_digits': max_digits},
|
| 393 |
+
)
|
| 394 |
+
return x
|
| 395 |
+
except TypeError:
|
| 396 |
+
raise TypeError(f"Unable to apply constraint 'max_digits' to supplied value {x}")
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def decimal_places_validator(x: Any, decimal_places: Any) -> Any:
|
| 400 |
+
try:
|
| 401 |
+
decimal_places_, _ = _extract_decimal_digits_info(x)
|
| 402 |
+
if decimal_places_ > decimal_places:
|
| 403 |
+
normalized_decimal_places, _ = _extract_decimal_digits_info(x.normalize())
|
| 404 |
+
if normalized_decimal_places > decimal_places:
|
| 405 |
+
raise PydanticKnownError(
|
| 406 |
+
'decimal_max_places',
|
| 407 |
+
{'decimal_places': decimal_places},
|
| 408 |
+
)
|
| 409 |
+
return x
|
| 410 |
+
except TypeError:
|
| 411 |
+
raise TypeError(f"Unable to apply constraint 'decimal_places' to supplied value {x}")
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def deque_validator(input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler) -> collections.deque[Any]:
|
| 415 |
+
return collections.deque(handler(input_value), maxlen=getattr(input_value, 'maxlen', None))
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def defaultdict_validator(
|
| 419 |
+
input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler, default_default_factory: Callable[[], Any]
|
| 420 |
+
) -> collections.defaultdict[Any, Any]:
|
| 421 |
+
if isinstance(input_value, collections.defaultdict):
|
| 422 |
+
default_factory = input_value.default_factory
|
| 423 |
+
return collections.defaultdict(default_factory, handler(input_value))
|
| 424 |
+
else:
|
| 425 |
+
return collections.defaultdict(default_default_factory, handler(input_value))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable[[], Any]:
|
| 429 |
+
FieldInfo = import_cached_field_info()
|
| 430 |
+
|
| 431 |
+
values_type_origin = get_origin(values_source_type)
|
| 432 |
+
|
| 433 |
+
def infer_default() -> Callable[[], Any]:
|
| 434 |
+
allowed_default_types: dict[Any, Any] = {
|
| 435 |
+
tuple: tuple,
|
| 436 |
+
collections.abc.Sequence: tuple,
|
| 437 |
+
collections.abc.MutableSequence: list,
|
| 438 |
+
list: list,
|
| 439 |
+
typing.Sequence: list,
|
| 440 |
+
set: set,
|
| 441 |
+
typing.MutableSet: set,
|
| 442 |
+
collections.abc.MutableSet: set,
|
| 443 |
+
collections.abc.Set: frozenset,
|
| 444 |
+
typing.MutableMapping: dict,
|
| 445 |
+
typing.Mapping: dict,
|
| 446 |
+
collections.abc.Mapping: dict,
|
| 447 |
+
collections.abc.MutableMapping: dict,
|
| 448 |
+
float: float,
|
| 449 |
+
int: int,
|
| 450 |
+
str: str,
|
| 451 |
+
bool: bool,
|
| 452 |
+
}
|
| 453 |
+
values_type = values_type_origin or values_source_type
|
| 454 |
+
instructions = 'set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]`'
|
| 455 |
+
if typing_objects.is_typevar(values_type):
|
| 456 |
+
|
| 457 |
+
def type_var_default_factory() -> None:
|
| 458 |
+
raise RuntimeError(
|
| 459 |
+
'Generic defaultdict cannot be used without a concrete value type or an'
|
| 460 |
+
' explicit default factory, ' + instructions
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
return type_var_default_factory
|
| 464 |
+
elif values_type not in allowed_default_types:
|
| 465 |
+
# a somewhat subjective set of types that have reasonable default values
|
| 466 |
+
allowed_msg = ', '.join([t.__name__ for t in set(allowed_default_types.values())])
|
| 467 |
+
raise PydanticSchemaGenerationError(
|
| 468 |
+
f'Unable to infer a default factory for keys of type {values_source_type}.'
|
| 469 |
+
f' Only {allowed_msg} are supported, other types require an explicit default factory'
|
| 470 |
+
' ' + instructions
|
| 471 |
+
)
|
| 472 |
+
return allowed_default_types[values_type]
|
| 473 |
+
|
| 474 |
+
# Assume Annotated[..., Field(...)]
|
| 475 |
+
if typing_objects.is_annotated(values_type_origin):
|
| 476 |
+
field_info = next((v for v in get_args(values_source_type) if isinstance(v, FieldInfo)), None)
|
| 477 |
+
else:
|
| 478 |
+
field_info = None
|
| 479 |
+
if field_info and field_info.default_factory:
|
| 480 |
+
# Assume the default factory does not take any argument:
|
| 481 |
+
default_default_factory = cast(Callable[[], Any], field_info.default_factory)
|
| 482 |
+
else:
|
| 483 |
+
default_default_factory = infer_default()
|
| 484 |
+
return default_default_factory
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def validate_str_is_valid_iana_tz(value: Any, /) -> ZoneInfo:
|
| 488 |
+
if isinstance(value, ZoneInfo):
|
| 489 |
+
return value
|
| 490 |
+
try:
|
| 491 |
+
return ZoneInfo(value)
|
| 492 |
+
except (ZoneInfoNotFoundError, ValueError, TypeError):
|
| 493 |
+
raise PydanticCustomError('zoneinfo_str', 'invalid timezone: {value}', {'value': value})
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
NUMERIC_VALIDATOR_LOOKUP: dict[str, Callable] = {
|
| 497 |
+
'gt': greater_than_validator,
|
| 498 |
+
'ge': greater_than_or_equal_validator,
|
| 499 |
+
'lt': less_than_validator,
|
| 500 |
+
'le': less_than_or_equal_validator,
|
| 501 |
+
'multiple_of': multiple_of_validator,
|
| 502 |
+
'min_length': min_length_validator,
|
| 503 |
+
'max_length': max_length_validator,
|
| 504 |
+
'max_digits': max_digits_validator,
|
| 505 |
+
'decimal_places': decimal_places_validator,
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
IpType = Union[IPv4Address, IPv6Address, IPv4Network, IPv6Network, IPv4Interface, IPv6Interface]
|
| 509 |
+
|
| 510 |
+
IP_VALIDATOR_LOOKUP: dict[type[IpType], Callable] = {
|
| 511 |
+
IPv4Address: ip_v4_address_validator,
|
| 512 |
+
IPv6Address: ip_v6_address_validator,
|
| 513 |
+
IPv4Network: ip_v4_network_validator,
|
| 514 |
+
IPv6Network: ip_v6_network_validator,
|
| 515 |
+
IPv4Interface: ip_v4_interface_validator,
|
| 516 |
+
IPv6Interface: ip_v6_interface_validator,
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
MAPPING_ORIGIN_MAP: dict[Any, Any] = {
|
| 520 |
+
typing.DefaultDict: collections.defaultdict, # noqa: UP006
|
| 521 |
+
collections.defaultdict: collections.defaultdict,
|
| 522 |
+
typing.OrderedDict: collections.OrderedDict, # noqa: UP006
|
| 523 |
+
collections.OrderedDict: collections.OrderedDict,
|
| 524 |
+
typing_extensions.OrderedDict: collections.OrderedDict,
|
| 525 |
+
typing.Counter: collections.Counter,
|
| 526 |
+
collections.Counter: collections.Counter,
|
| 527 |
+
# this doesn't handle subclasses of these
|
| 528 |
+
typing.Mapping: dict,
|
| 529 |
+
typing.MutableMapping: dict,
|
| 530 |
+
# parametrized typing.{Mutable}Mapping creates one of these
|
| 531 |
+
collections.abc.Mapping: dict,
|
| 532 |
+
collections.abc.MutableMapping: dict,
|
| 533 |
+
}
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/__init__.py
ADDED
|
File without changes
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/class_valid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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Old `@validator` and `@root_validator` function validators from V1."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations as _annotations
|
| 4 |
+
|
| 5 |
+
from functools import partial, partialmethod
|
| 6 |
+
from types import FunctionType
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, overload
|
| 8 |
+
from warnings import warn
|
| 9 |
+
|
| 10 |
+
from typing_extensions import Protocol, TypeAlias, deprecated
|
| 11 |
+
|
| 12 |
+
from .._internal import _decorators, _decorators_v1
|
| 13 |
+
from ..errors import PydanticUserError
|
| 14 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 15 |
+
|
| 16 |
+
_ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
|
| 21 |
+
class _OnlyValueValidatorClsMethod(Protocol):
|
| 22 |
+
def __call__(self, __cls: Any, __value: Any) -> Any: ...
|
| 23 |
+
|
| 24 |
+
class _V1ValidatorWithValuesClsMethod(Protocol):
|
| 25 |
+
def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any: ...
|
| 26 |
+
|
| 27 |
+
class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol):
|
| 28 |
+
def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any: ...
|
| 29 |
+
|
| 30 |
+
class _V1ValidatorWithKwargsClsMethod(Protocol):
|
| 31 |
+
def __call__(self, __cls: Any, **kwargs: Any) -> Any: ...
|
| 32 |
+
|
| 33 |
+
class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol):
|
| 34 |
+
def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
|
| 35 |
+
|
| 36 |
+
class _V1RootValidatorClsMethod(Protocol):
|
| 37 |
+
def __call__(
|
| 38 |
+
self, __cls: Any, __values: _decorators_v1.RootValidatorValues
|
| 39 |
+
) -> _decorators_v1.RootValidatorValues: ...
|
| 40 |
+
|
| 41 |
+
V1Validator = Union[
|
| 42 |
+
_OnlyValueValidatorClsMethod,
|
| 43 |
+
_V1ValidatorWithValuesClsMethod,
|
| 44 |
+
_V1ValidatorWithValuesKwOnlyClsMethod,
|
| 45 |
+
_V1ValidatorWithKwargsClsMethod,
|
| 46 |
+
_V1ValidatorWithValuesAndKwargsClsMethod,
|
| 47 |
+
_decorators_v1.V1ValidatorWithValues,
|
| 48 |
+
_decorators_v1.V1ValidatorWithValuesKwOnly,
|
| 49 |
+
_decorators_v1.V1ValidatorWithKwargs,
|
| 50 |
+
_decorators_v1.V1ValidatorWithValuesAndKwargs,
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
V1RootValidator = Union[
|
| 54 |
+
_V1RootValidatorClsMethod,
|
| 55 |
+
_decorators_v1.V1RootValidatorFunction,
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
_PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
|
| 59 |
+
|
| 60 |
+
# Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator
|
| 61 |
+
# We lie to type checkers and say we return the same thing we get
|
| 62 |
+
# but in reality we return a proxy object that _mostly_ behaves like the wrapped thing
|
| 63 |
+
_V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod)
|
| 64 |
+
_V1RootValidatorFunctionType = TypeVar(
|
| 65 |
+
'_V1RootValidatorFunctionType',
|
| 66 |
+
_decorators_v1.V1RootValidatorFunction,
|
| 67 |
+
_V1RootValidatorClsMethod,
|
| 68 |
+
_PartialClsOrStaticMethod,
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 72 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 73 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@deprecated(
|
| 77 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
| 78 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
| 79 |
+
' see the migration guide for more details',
|
| 80 |
+
category=None,
|
| 81 |
+
)
|
| 82 |
+
def validator(
|
| 83 |
+
__field: str,
|
| 84 |
+
*fields: str,
|
| 85 |
+
pre: bool = False,
|
| 86 |
+
each_item: bool = False,
|
| 87 |
+
always: bool = False,
|
| 88 |
+
check_fields: bool | None = None,
|
| 89 |
+
allow_reuse: bool = False,
|
| 90 |
+
) -> Callable[[_V1ValidatorType], _V1ValidatorType]:
|
| 91 |
+
"""Decorate methods on the class indicating that they should be used to validate fields.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
__field (str): The first field the validator should be called on; this is separate
|
| 95 |
+
from `fields` to ensure an error is raised if you don't pass at least one.
|
| 96 |
+
*fields (str): Additional field(s) the validator should be called on.
|
| 97 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
| 98 |
+
validators (else after). Defaults to False.
|
| 99 |
+
each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate
|
| 100 |
+
individual elements rather than the whole object. Defaults to False.
|
| 101 |
+
always (bool, optional): Whether this method and other validators should be called even if
|
| 102 |
+
the value is missing. Defaults to False.
|
| 103 |
+
check_fields (bool | None, optional): Whether to check that the fields actually exist on the model.
|
| 104 |
+
Defaults to None.
|
| 105 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to
|
| 106 |
+
the decorated function. Defaults to False.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Callable: A decorator that can be used to decorate a
|
| 110 |
+
function to be used as a validator.
|
| 111 |
+
"""
|
| 112 |
+
warn(
|
| 113 |
+
'Pydantic V1 style `@validator` validators are deprecated.'
|
| 114 |
+
' You should migrate to Pydantic V2 style `@field_validator` validators,'
|
| 115 |
+
' see the migration guide for more details',
|
| 116 |
+
DeprecationWarning,
|
| 117 |
+
stacklevel=2,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
if allow_reuse is True: # pragma: no cover
|
| 121 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
|
| 122 |
+
fields = __field, *fields
|
| 123 |
+
if isinstance(fields[0], FunctionType):
|
| 124 |
+
raise PydanticUserError(
|
| 125 |
+
'`@validator` should be used with fields and keyword arguments, not bare. '
|
| 126 |
+
"E.g. usage should be `@validator('<field_name>', ...)`",
|
| 127 |
+
code='validator-no-fields',
|
| 128 |
+
)
|
| 129 |
+
elif not all(isinstance(field, str) for field in fields):
|
| 130 |
+
raise PydanticUserError(
|
| 131 |
+
'`@validator` fields should be passed as separate string args. '
|
| 132 |
+
"E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
|
| 133 |
+
code='validator-invalid-fields',
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
| 137 |
+
|
| 138 |
+
def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
|
| 139 |
+
if _decorators.is_instance_method_from_sig(f):
|
| 140 |
+
raise PydanticUserError(
|
| 141 |
+
'`@validator` cannot be applied to instance methods', code='validator-instance-method'
|
| 142 |
+
)
|
| 143 |
+
# auto apply the @classmethod decorator
|
| 144 |
+
f = _decorators.ensure_classmethod_based_on_signature(f)
|
| 145 |
+
wrap = _decorators_v1.make_generic_v1_field_validator
|
| 146 |
+
validator_wrapper_info = _decorators.ValidatorDecoratorInfo(
|
| 147 |
+
fields=fields,
|
| 148 |
+
mode=mode,
|
| 149 |
+
each_item=each_item,
|
| 150 |
+
always=always,
|
| 151 |
+
check_fields=check_fields,
|
| 152 |
+
)
|
| 153 |
+
return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap)
|
| 154 |
+
|
| 155 |
+
return dec # type: ignore[return-value]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@overload
|
| 159 |
+
def root_validator(
|
| 160 |
+
*,
|
| 161 |
+
# if you don't specify `pre` the default is `pre=False`
|
| 162 |
+
# which means you need to specify `skip_on_failure=True`
|
| 163 |
+
skip_on_failure: Literal[True],
|
| 164 |
+
allow_reuse: bool = ...,
|
| 165 |
+
) -> Callable[
|
| 166 |
+
[_V1RootValidatorFunctionType],
|
| 167 |
+
_V1RootValidatorFunctionType,
|
| 168 |
+
]: ...
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@overload
|
| 172 |
+
def root_validator(
|
| 173 |
+
*,
|
| 174 |
+
# if you specify `pre=True` then you don't need to specify
|
| 175 |
+
# `skip_on_failure`, in fact it is not allowed as an argument!
|
| 176 |
+
pre: Literal[True],
|
| 177 |
+
allow_reuse: bool = ...,
|
| 178 |
+
) -> Callable[
|
| 179 |
+
[_V1RootValidatorFunctionType],
|
| 180 |
+
_V1RootValidatorFunctionType,
|
| 181 |
+
]: ...
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@overload
|
| 185 |
+
def root_validator(
|
| 186 |
+
*,
|
| 187 |
+
# if you explicitly specify `pre=False` then you
|
| 188 |
+
# MUST specify `skip_on_failure=True`
|
| 189 |
+
pre: Literal[False],
|
| 190 |
+
skip_on_failure: Literal[True],
|
| 191 |
+
allow_reuse: bool = ...,
|
| 192 |
+
) -> Callable[
|
| 193 |
+
[_V1RootValidatorFunctionType],
|
| 194 |
+
_V1RootValidatorFunctionType,
|
| 195 |
+
]: ...
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@deprecated(
|
| 199 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
| 200 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
| 201 |
+
' see the migration guide for more details',
|
| 202 |
+
category=None,
|
| 203 |
+
)
|
| 204 |
+
def root_validator(
|
| 205 |
+
*__args,
|
| 206 |
+
pre: bool = False,
|
| 207 |
+
skip_on_failure: bool = False,
|
| 208 |
+
allow_reuse: bool = False,
|
| 209 |
+
) -> Any:
|
| 210 |
+
"""Decorate methods on a model indicating that they should be used to validate (and perhaps
|
| 211 |
+
modify) data either before or after standard model parsing/validation is performed.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
pre (bool, optional): Whether this validator should be called before the standard
|
| 215 |
+
validators (else after). Defaults to False.
|
| 216 |
+
skip_on_failure (bool, optional): Whether to stop validation and return as soon as a
|
| 217 |
+
failure is encountered. Defaults to False.
|
| 218 |
+
allow_reuse (bool, optional): Whether to track and raise an error if another validator
|
| 219 |
+
refers to the decorated function. Defaults to False.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
Any: A decorator that can be used to decorate a function to be used as a root_validator.
|
| 223 |
+
"""
|
| 224 |
+
warn(
|
| 225 |
+
'Pydantic V1 style `@root_validator` validators are deprecated.'
|
| 226 |
+
' You should migrate to Pydantic V2 style `@model_validator` validators,'
|
| 227 |
+
' see the migration guide for more details',
|
| 228 |
+
DeprecationWarning,
|
| 229 |
+
stacklevel=2,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if __args:
|
| 233 |
+
# Ensure a nice error is raised if someone attempts to use the bare decorator
|
| 234 |
+
return root_validator()(*__args) # type: ignore
|
| 235 |
+
|
| 236 |
+
if allow_reuse is True: # pragma: no cover
|
| 237 |
+
warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
|
| 238 |
+
mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
|
| 239 |
+
if pre is False and skip_on_failure is not True:
|
| 240 |
+
raise PydanticUserError(
|
| 241 |
+
'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.'
|
| 242 |
+
' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.',
|
| 243 |
+
code='root-validator-pre-skip',
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre)
|
| 247 |
+
|
| 248 |
+
def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any:
|
| 249 |
+
if _decorators.is_instance_method_from_sig(f):
|
| 250 |
+
raise TypeError('`@root_validator` cannot be applied to instance methods')
|
| 251 |
+
# auto apply the @classmethod decorator
|
| 252 |
+
res = _decorators.ensure_classmethod_based_on_signature(f)
|
| 253 |
+
dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode)
|
| 254 |
+
return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap)
|
| 255 |
+
|
| 256 |
+
return dec
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/config.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Literal
|
| 5 |
+
|
| 6 |
+
from typing_extensions import deprecated
|
| 7 |
+
|
| 8 |
+
from .._internal import _config
|
| 9 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 10 |
+
|
| 11 |
+
if not TYPE_CHECKING:
|
| 12 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 13 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 14 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 15 |
+
|
| 16 |
+
__all__ = 'BaseConfig', 'Extra'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _ConfigMetaclass(type):
|
| 20 |
+
def __getattr__(self, item: str) -> Any:
|
| 21 |
+
try:
|
| 22 |
+
obj = _config.config_defaults[item]
|
| 23 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 24 |
+
return obj
|
| 25 |
+
except KeyError as exc:
|
| 26 |
+
raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@deprecated('BaseConfig is deprecated. Use the `pydantic.ConfigDict` instead.', category=PydanticDeprecatedSince20)
|
| 30 |
+
class BaseConfig(metaclass=_ConfigMetaclass):
|
| 31 |
+
"""This class is only retained for backwards compatibility.
|
| 32 |
+
|
| 33 |
+
!!! Warning "Deprecated"
|
| 34 |
+
BaseConfig is deprecated. Use the [`pydantic.ConfigDict`][pydantic.ConfigDict] instead.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __getattr__(self, item: str) -> Any:
|
| 38 |
+
try:
|
| 39 |
+
obj = super().__getattribute__(item)
|
| 40 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 41 |
+
return obj
|
| 42 |
+
except AttributeError as exc:
|
| 43 |
+
try:
|
| 44 |
+
return getattr(type(self), item)
|
| 45 |
+
except AttributeError:
|
| 46 |
+
# re-raising changes the displayed text to reflect that `self` is not a type
|
| 47 |
+
raise AttributeError(str(exc)) from exc
|
| 48 |
+
|
| 49 |
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
| 50 |
+
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
|
| 51 |
+
return super().__init_subclass__(**kwargs)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class _ExtraMeta(type):
|
| 55 |
+
def __getattribute__(self, __name: str) -> Any:
|
| 56 |
+
# The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones
|
| 57 |
+
if __name in {'allow', 'ignore', 'forbid'}:
|
| 58 |
+
warnings.warn(
|
| 59 |
+
"`pydantic.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)",
|
| 60 |
+
DeprecationWarning,
|
| 61 |
+
stacklevel=2,
|
| 62 |
+
)
|
| 63 |
+
return super().__getattribute__(__name)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@deprecated(
|
| 67 |
+
"Extra is deprecated. Use literal values instead (e.g. `extra='allow'`)", category=PydanticDeprecatedSince20
|
| 68 |
+
)
|
| 69 |
+
class Extra(metaclass=_ExtraMeta):
|
| 70 |
+
allow: Literal['allow'] = 'allow'
|
| 71 |
+
ignore: Literal['ignore'] = 'ignore'
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations as _annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import typing_extensions
|
| 9 |
+
|
| 10 |
+
from .._internal import (
|
| 11 |
+
_model_construction,
|
| 12 |
+
_typing_extra,
|
| 13 |
+
_utils,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
if typing.TYPE_CHECKING:
|
| 17 |
+
from .. import BaseModel
|
| 18 |
+
from .._internal._utils import AbstractSetIntStr, MappingIntStrAny
|
| 19 |
+
|
| 20 |
+
AnyClassMethod = classmethod[Any, Any, Any]
|
| 21 |
+
TupleGenerator = typing.Generator[tuple[str, Any], None, None]
|
| 22 |
+
Model = typing.TypeVar('Model', bound='BaseModel')
|
| 23 |
+
# should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope
|
| 24 |
+
IncEx: typing_extensions.TypeAlias = 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None'
|
| 25 |
+
|
| 26 |
+
_object_setattr = _model_construction.object_setattr
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _iter(
|
| 30 |
+
self: BaseModel,
|
| 31 |
+
to_dict: bool = False,
|
| 32 |
+
by_alias: bool = False,
|
| 33 |
+
include: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 34 |
+
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
|
| 35 |
+
exclude_unset: bool = False,
|
| 36 |
+
exclude_defaults: bool = False,
|
| 37 |
+
exclude_none: bool = False,
|
| 38 |
+
) -> TupleGenerator:
|
| 39 |
+
# Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
|
| 40 |
+
# The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
|
| 41 |
+
if exclude is not None:
|
| 42 |
+
exclude = _utils.ValueItems.merge(
|
| 43 |
+
{k: v.exclude for k, v in self.__pydantic_fields__.items() if v.exclude is not None}, exclude
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if include is not None:
|
| 47 |
+
include = _utils.ValueItems.merge(dict.fromkeys(self.__pydantic_fields__, True), include, intersect=True)
|
| 48 |
+
|
| 49 |
+
allowed_keys = _calculate_keys(self, include=include, exclude=exclude, exclude_unset=exclude_unset) # type: ignore
|
| 50 |
+
if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
|
| 51 |
+
# huge boost for plain _iter()
|
| 52 |
+
yield from self.__dict__.items()
|
| 53 |
+
if self.__pydantic_extra__:
|
| 54 |
+
yield from self.__pydantic_extra__.items()
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
value_exclude = _utils.ValueItems(self, exclude) if exclude is not None else None
|
| 58 |
+
value_include = _utils.ValueItems(self, include) if include is not None else None
|
| 59 |
+
|
| 60 |
+
if self.__pydantic_extra__ is None:
|
| 61 |
+
items = self.__dict__.items()
|
| 62 |
+
else:
|
| 63 |
+
items = list(self.__dict__.items()) + list(self.__pydantic_extra__.items())
|
| 64 |
+
|
| 65 |
+
for field_key, v in items:
|
| 66 |
+
if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
if exclude_defaults:
|
| 70 |
+
try:
|
| 71 |
+
field = self.__pydantic_fields__[field_key]
|
| 72 |
+
except KeyError:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
if not field.is_required() and field.default == v:
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
if by_alias and field_key in self.__pydantic_fields__:
|
| 79 |
+
dict_key = self.__pydantic_fields__[field_key].alias or field_key
|
| 80 |
+
else:
|
| 81 |
+
dict_key = field_key
|
| 82 |
+
|
| 83 |
+
if to_dict or value_include or value_exclude:
|
| 84 |
+
v = _get_value(
|
| 85 |
+
type(self),
|
| 86 |
+
v,
|
| 87 |
+
to_dict=to_dict,
|
| 88 |
+
by_alias=by_alias,
|
| 89 |
+
include=value_include and value_include.for_element(field_key),
|
| 90 |
+
exclude=value_exclude and value_exclude.for_element(field_key),
|
| 91 |
+
exclude_unset=exclude_unset,
|
| 92 |
+
exclude_defaults=exclude_defaults,
|
| 93 |
+
exclude_none=exclude_none,
|
| 94 |
+
)
|
| 95 |
+
yield dict_key, v
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _copy_and_set_values(
|
| 99 |
+
self: Model,
|
| 100 |
+
values: dict[str, Any],
|
| 101 |
+
fields_set: set[str],
|
| 102 |
+
extra: dict[str, Any] | None = None,
|
| 103 |
+
private: dict[str, Any] | None = None,
|
| 104 |
+
*,
|
| 105 |
+
deep: bool, # UP006
|
| 106 |
+
) -> Model:
|
| 107 |
+
if deep:
|
| 108 |
+
# chances of having empty dict here are quite low for using smart_deepcopy
|
| 109 |
+
values = deepcopy(values)
|
| 110 |
+
extra = deepcopy(extra)
|
| 111 |
+
private = deepcopy(private)
|
| 112 |
+
|
| 113 |
+
cls = self.__class__
|
| 114 |
+
m = cls.__new__(cls)
|
| 115 |
+
_object_setattr(m, '__dict__', values)
|
| 116 |
+
_object_setattr(m, '__pydantic_extra__', extra)
|
| 117 |
+
_object_setattr(m, '__pydantic_fields_set__', fields_set)
|
| 118 |
+
_object_setattr(m, '__pydantic_private__', private)
|
| 119 |
+
|
| 120 |
+
return m
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@typing.no_type_check
|
| 124 |
+
def _get_value(
|
| 125 |
+
cls: type[BaseModel],
|
| 126 |
+
v: Any,
|
| 127 |
+
to_dict: bool,
|
| 128 |
+
by_alias: bool,
|
| 129 |
+
include: AbstractSetIntStr | MappingIntStrAny | None,
|
| 130 |
+
exclude: AbstractSetIntStr | MappingIntStrAny | None,
|
| 131 |
+
exclude_unset: bool,
|
| 132 |
+
exclude_defaults: bool,
|
| 133 |
+
exclude_none: bool,
|
| 134 |
+
) -> Any:
|
| 135 |
+
from .. import BaseModel
|
| 136 |
+
|
| 137 |
+
if isinstance(v, BaseModel):
|
| 138 |
+
if to_dict:
|
| 139 |
+
return v.model_dump(
|
| 140 |
+
by_alias=by_alias,
|
| 141 |
+
exclude_unset=exclude_unset,
|
| 142 |
+
exclude_defaults=exclude_defaults,
|
| 143 |
+
include=include, # type: ignore
|
| 144 |
+
exclude=exclude, # type: ignore
|
| 145 |
+
exclude_none=exclude_none,
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
return v.copy(include=include, exclude=exclude)
|
| 149 |
+
|
| 150 |
+
value_exclude = _utils.ValueItems(v, exclude) if exclude else None
|
| 151 |
+
value_include = _utils.ValueItems(v, include) if include else None
|
| 152 |
+
|
| 153 |
+
if isinstance(v, dict):
|
| 154 |
+
return {
|
| 155 |
+
k_: _get_value(
|
| 156 |
+
cls,
|
| 157 |
+
v_,
|
| 158 |
+
to_dict=to_dict,
|
| 159 |
+
by_alias=by_alias,
|
| 160 |
+
exclude_unset=exclude_unset,
|
| 161 |
+
exclude_defaults=exclude_defaults,
|
| 162 |
+
include=value_include and value_include.for_element(k_),
|
| 163 |
+
exclude=value_exclude and value_exclude.for_element(k_),
|
| 164 |
+
exclude_none=exclude_none,
|
| 165 |
+
)
|
| 166 |
+
for k_, v_ in v.items()
|
| 167 |
+
if (not value_exclude or not value_exclude.is_excluded(k_))
|
| 168 |
+
and (not value_include or value_include.is_included(k_))
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
elif _utils.sequence_like(v):
|
| 172 |
+
seq_args = (
|
| 173 |
+
_get_value(
|
| 174 |
+
cls,
|
| 175 |
+
v_,
|
| 176 |
+
to_dict=to_dict,
|
| 177 |
+
by_alias=by_alias,
|
| 178 |
+
exclude_unset=exclude_unset,
|
| 179 |
+
exclude_defaults=exclude_defaults,
|
| 180 |
+
include=value_include and value_include.for_element(i),
|
| 181 |
+
exclude=value_exclude and value_exclude.for_element(i),
|
| 182 |
+
exclude_none=exclude_none,
|
| 183 |
+
)
|
| 184 |
+
for i, v_ in enumerate(v)
|
| 185 |
+
if (not value_exclude or not value_exclude.is_excluded(i))
|
| 186 |
+
and (not value_include or value_include.is_included(i))
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return v.__class__(*seq_args) if _typing_extra.is_namedtuple(v.__class__) else v.__class__(seq_args)
|
| 190 |
+
|
| 191 |
+
elif isinstance(v, Enum) and getattr(cls.model_config, 'use_enum_values', False):
|
| 192 |
+
return v.value
|
| 193 |
+
|
| 194 |
+
else:
|
| 195 |
+
return v
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _calculate_keys(
|
| 199 |
+
self: BaseModel,
|
| 200 |
+
include: MappingIntStrAny | None,
|
| 201 |
+
exclude: MappingIntStrAny | None,
|
| 202 |
+
exclude_unset: bool,
|
| 203 |
+
update: dict[str, Any] | None = None, # noqa UP006
|
| 204 |
+
) -> typing.AbstractSet[str] | None:
|
| 205 |
+
if include is None and exclude is None and exclude_unset is False:
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
keys: typing.AbstractSet[str]
|
| 209 |
+
if exclude_unset:
|
| 210 |
+
keys = self.__pydantic_fields_set__.copy()
|
| 211 |
+
else:
|
| 212 |
+
keys = set(self.__dict__.keys())
|
| 213 |
+
keys = keys | (self.__pydantic_extra__ or {}).keys()
|
| 214 |
+
|
| 215 |
+
if include is not None:
|
| 216 |
+
keys &= include.keys()
|
| 217 |
+
|
| 218 |
+
if update:
|
| 219 |
+
keys -= update.keys()
|
| 220 |
+
|
| 221 |
+
if exclude:
|
| 222 |
+
keys -= {k for k, v in exclude.items() if _utils.ValueItems.is_true(v)}
|
| 223 |
+
|
| 224 |
+
return keys
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/decorator.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from collections.abc import Mapping
|
| 3 |
+
from functools import wraps
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, overload
|
| 5 |
+
|
| 6 |
+
from typing_extensions import deprecated
|
| 7 |
+
|
| 8 |
+
from .._internal import _config, _typing_extra
|
| 9 |
+
from ..alias_generators import to_pascal
|
| 10 |
+
from ..errors import PydanticUserError
|
| 11 |
+
from ..functional_validators import field_validator
|
| 12 |
+
from ..main import BaseModel, create_model
|
| 13 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 14 |
+
|
| 15 |
+
if not TYPE_CHECKING:
|
| 16 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 17 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 18 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 19 |
+
|
| 20 |
+
__all__ = ('validate_arguments',)
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
AnyCallable = Callable[..., Any]
|
| 24 |
+
|
| 25 |
+
AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
|
| 26 |
+
ConfigType = Union[None, type[Any], dict[str, Any]]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@overload
|
| 30 |
+
def validate_arguments(
|
| 31 |
+
func: None = None, *, config: 'ConfigType' = None
|
| 32 |
+
) -> Callable[['AnyCallableT'], 'AnyCallableT']: ...
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@overload
|
| 36 |
+
def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': ...
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@deprecated(
|
| 40 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
| 41 |
+
category=None,
|
| 42 |
+
)
|
| 43 |
+
def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
|
| 44 |
+
"""Decorator to validate the arguments passed to a function."""
|
| 45 |
+
warnings.warn(
|
| 46 |
+
'The `validate_arguments` method is deprecated; use `validate_call` instead.',
|
| 47 |
+
PydanticDeprecatedSince20,
|
| 48 |
+
stacklevel=2,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def validate(_func: 'AnyCallable') -> 'AnyCallable':
|
| 52 |
+
vd = ValidatedFunction(_func, config)
|
| 53 |
+
|
| 54 |
+
@wraps(_func)
|
| 55 |
+
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
|
| 56 |
+
return vd.call(*args, **kwargs)
|
| 57 |
+
|
| 58 |
+
wrapper_function.vd = vd # type: ignore
|
| 59 |
+
wrapper_function.validate = vd.init_model_instance # type: ignore
|
| 60 |
+
wrapper_function.raw_function = vd.raw_function # type: ignore
|
| 61 |
+
wrapper_function.model = vd.model # type: ignore
|
| 62 |
+
return wrapper_function
|
| 63 |
+
|
| 64 |
+
if func:
|
| 65 |
+
return validate(func)
|
| 66 |
+
else:
|
| 67 |
+
return validate
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
ALT_V_ARGS = 'v__args'
|
| 71 |
+
ALT_V_KWARGS = 'v__kwargs'
|
| 72 |
+
V_POSITIONAL_ONLY_NAME = 'v__positional_only'
|
| 73 |
+
V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ValidatedFunction:
|
| 77 |
+
def __init__(self, function: 'AnyCallable', config: 'ConfigType'):
|
| 78 |
+
from inspect import Parameter, signature
|
| 79 |
+
|
| 80 |
+
parameters: Mapping[str, Parameter] = signature(function).parameters
|
| 81 |
+
|
| 82 |
+
if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
|
| 83 |
+
raise PydanticUserError(
|
| 84 |
+
f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
|
| 85 |
+
f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
|
| 86 |
+
code=None,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self.raw_function = function
|
| 90 |
+
self.arg_mapping: dict[int, str] = {}
|
| 91 |
+
self.positional_only_args: set[str] = set()
|
| 92 |
+
self.v_args_name = 'args'
|
| 93 |
+
self.v_kwargs_name = 'kwargs'
|
| 94 |
+
|
| 95 |
+
type_hints = _typing_extra.get_type_hints(function, include_extras=True)
|
| 96 |
+
takes_args = False
|
| 97 |
+
takes_kwargs = False
|
| 98 |
+
fields: dict[str, tuple[Any, Any]] = {}
|
| 99 |
+
for i, (name, p) in enumerate(parameters.items()):
|
| 100 |
+
if p.annotation is p.empty:
|
| 101 |
+
annotation = Any
|
| 102 |
+
else:
|
| 103 |
+
annotation = type_hints[name]
|
| 104 |
+
|
| 105 |
+
default = ... if p.default is p.empty else p.default
|
| 106 |
+
if p.kind == Parameter.POSITIONAL_ONLY:
|
| 107 |
+
self.arg_mapping[i] = name
|
| 108 |
+
fields[name] = annotation, default
|
| 109 |
+
fields[V_POSITIONAL_ONLY_NAME] = list[str], None
|
| 110 |
+
self.positional_only_args.add(name)
|
| 111 |
+
elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
|
| 112 |
+
self.arg_mapping[i] = name
|
| 113 |
+
fields[name] = annotation, default
|
| 114 |
+
fields[V_DUPLICATE_KWARGS] = list[str], None
|
| 115 |
+
elif p.kind == Parameter.KEYWORD_ONLY:
|
| 116 |
+
fields[name] = annotation, default
|
| 117 |
+
elif p.kind == Parameter.VAR_POSITIONAL:
|
| 118 |
+
self.v_args_name = name
|
| 119 |
+
fields[name] = tuple[annotation, ...], None
|
| 120 |
+
takes_args = True
|
| 121 |
+
else:
|
| 122 |
+
assert p.kind == Parameter.VAR_KEYWORD, p.kind
|
| 123 |
+
self.v_kwargs_name = name
|
| 124 |
+
fields[name] = dict[str, annotation], None
|
| 125 |
+
takes_kwargs = True
|
| 126 |
+
|
| 127 |
+
# these checks avoid a clash between "args" and a field with that name
|
| 128 |
+
if not takes_args and self.v_args_name in fields:
|
| 129 |
+
self.v_args_name = ALT_V_ARGS
|
| 130 |
+
|
| 131 |
+
# same with "kwargs"
|
| 132 |
+
if not takes_kwargs and self.v_kwargs_name in fields:
|
| 133 |
+
self.v_kwargs_name = ALT_V_KWARGS
|
| 134 |
+
|
| 135 |
+
if not takes_args:
|
| 136 |
+
# we add the field so validation below can raise the correct exception
|
| 137 |
+
fields[self.v_args_name] = list[Any], None
|
| 138 |
+
|
| 139 |
+
if not takes_kwargs:
|
| 140 |
+
# same with kwargs
|
| 141 |
+
fields[self.v_kwargs_name] = dict[Any, Any], None
|
| 142 |
+
|
| 143 |
+
self.create_model(fields, takes_args, takes_kwargs, config)
|
| 144 |
+
|
| 145 |
+
def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
|
| 146 |
+
values = self.build_values(args, kwargs)
|
| 147 |
+
return self.model(**values)
|
| 148 |
+
|
| 149 |
+
def call(self, *args: Any, **kwargs: Any) -> Any:
|
| 150 |
+
m = self.init_model_instance(*args, **kwargs)
|
| 151 |
+
return self.execute(m)
|
| 152 |
+
|
| 153 |
+
def build_values(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]:
|
| 154 |
+
values: dict[str, Any] = {}
|
| 155 |
+
if args:
|
| 156 |
+
arg_iter = enumerate(args)
|
| 157 |
+
while True:
|
| 158 |
+
try:
|
| 159 |
+
i, a = next(arg_iter)
|
| 160 |
+
except StopIteration:
|
| 161 |
+
break
|
| 162 |
+
arg_name = self.arg_mapping.get(i)
|
| 163 |
+
if arg_name is not None:
|
| 164 |
+
values[arg_name] = a
|
| 165 |
+
else:
|
| 166 |
+
values[self.v_args_name] = [a] + [a for _, a in arg_iter]
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
var_kwargs: dict[str, Any] = {}
|
| 170 |
+
wrong_positional_args = []
|
| 171 |
+
duplicate_kwargs = []
|
| 172 |
+
fields_alias = [
|
| 173 |
+
field.alias
|
| 174 |
+
for name, field in self.model.__pydantic_fields__.items()
|
| 175 |
+
if name not in (self.v_args_name, self.v_kwargs_name)
|
| 176 |
+
]
|
| 177 |
+
non_var_fields = set(self.model.__pydantic_fields__) - {self.v_args_name, self.v_kwargs_name}
|
| 178 |
+
for k, v in kwargs.items():
|
| 179 |
+
if k in non_var_fields or k in fields_alias:
|
| 180 |
+
if k in self.positional_only_args:
|
| 181 |
+
wrong_positional_args.append(k)
|
| 182 |
+
if k in values:
|
| 183 |
+
duplicate_kwargs.append(k)
|
| 184 |
+
values[k] = v
|
| 185 |
+
else:
|
| 186 |
+
var_kwargs[k] = v
|
| 187 |
+
|
| 188 |
+
if var_kwargs:
|
| 189 |
+
values[self.v_kwargs_name] = var_kwargs
|
| 190 |
+
if wrong_positional_args:
|
| 191 |
+
values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
|
| 192 |
+
if duplicate_kwargs:
|
| 193 |
+
values[V_DUPLICATE_KWARGS] = duplicate_kwargs
|
| 194 |
+
return values
|
| 195 |
+
|
| 196 |
+
def execute(self, m: BaseModel) -> Any:
|
| 197 |
+
d = {
|
| 198 |
+
k: v
|
| 199 |
+
for k, v in m.__dict__.items()
|
| 200 |
+
if k in m.__pydantic_fields_set__ or m.__pydantic_fields__[k].default_factory
|
| 201 |
+
}
|
| 202 |
+
var_kwargs = d.pop(self.v_kwargs_name, {})
|
| 203 |
+
|
| 204 |
+
if self.v_args_name in d:
|
| 205 |
+
args_: list[Any] = []
|
| 206 |
+
in_kwargs = False
|
| 207 |
+
kwargs = {}
|
| 208 |
+
for name, value in d.items():
|
| 209 |
+
if in_kwargs:
|
| 210 |
+
kwargs[name] = value
|
| 211 |
+
elif name == self.v_args_name:
|
| 212 |
+
args_ += value
|
| 213 |
+
in_kwargs = True
|
| 214 |
+
else:
|
| 215 |
+
args_.append(value)
|
| 216 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
| 217 |
+
elif self.positional_only_args:
|
| 218 |
+
args_ = []
|
| 219 |
+
kwargs = {}
|
| 220 |
+
for name, value in d.items():
|
| 221 |
+
if name in self.positional_only_args:
|
| 222 |
+
args_.append(value)
|
| 223 |
+
else:
|
| 224 |
+
kwargs[name] = value
|
| 225 |
+
return self.raw_function(*args_, **kwargs, **var_kwargs)
|
| 226 |
+
else:
|
| 227 |
+
return self.raw_function(**d, **var_kwargs)
|
| 228 |
+
|
| 229 |
+
def create_model(self, fields: dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
|
| 230 |
+
pos_args = len(self.arg_mapping)
|
| 231 |
+
|
| 232 |
+
config_wrapper = _config.ConfigWrapper(config)
|
| 233 |
+
|
| 234 |
+
if config_wrapper.alias_generator:
|
| 235 |
+
raise PydanticUserError(
|
| 236 |
+
'Setting the "alias_generator" property on custom Config for '
|
| 237 |
+
'@validate_arguments is not yet supported, please remove.',
|
| 238 |
+
code=None,
|
| 239 |
+
)
|
| 240 |
+
if config_wrapper.extra is None:
|
| 241 |
+
config_wrapper.config_dict['extra'] = 'forbid'
|
| 242 |
+
|
| 243 |
+
class DecoratorBaseModel(BaseModel):
|
| 244 |
+
@field_validator(self.v_args_name, check_fields=False)
|
| 245 |
+
@classmethod
|
| 246 |
+
def check_args(cls, v: Optional[list[Any]]) -> Optional[list[Any]]:
|
| 247 |
+
if takes_args or v is None:
|
| 248 |
+
return v
|
| 249 |
+
|
| 250 |
+
raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
|
| 251 |
+
|
| 252 |
+
@field_validator(self.v_kwargs_name, check_fields=False)
|
| 253 |
+
@classmethod
|
| 254 |
+
def check_kwargs(cls, v: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
|
| 255 |
+
if takes_kwargs or v is None:
|
| 256 |
+
return v
|
| 257 |
+
|
| 258 |
+
plural = '' if len(v) == 1 else 's'
|
| 259 |
+
keys = ', '.join(map(repr, v.keys()))
|
| 260 |
+
raise TypeError(f'unexpected keyword argument{plural}: {keys}')
|
| 261 |
+
|
| 262 |
+
@field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
|
| 263 |
+
@classmethod
|
| 264 |
+
def check_positional_only(cls, v: Optional[list[str]]) -> None:
|
| 265 |
+
if v is None:
|
| 266 |
+
return
|
| 267 |
+
|
| 268 |
+
plural = '' if len(v) == 1 else 's'
|
| 269 |
+
keys = ', '.join(map(repr, v))
|
| 270 |
+
raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
|
| 271 |
+
|
| 272 |
+
@field_validator(V_DUPLICATE_KWARGS, check_fields=False)
|
| 273 |
+
@classmethod
|
| 274 |
+
def check_duplicate_kwargs(cls, v: Optional[list[str]]) -> None:
|
| 275 |
+
if v is None:
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
plural = '' if len(v) == 1 else 's'
|
| 279 |
+
keys = ', '.join(map(repr, v))
|
| 280 |
+
raise TypeError(f'multiple values for argument{plural}: {keys}')
|
| 281 |
+
|
| 282 |
+
model_config = config_wrapper.config_dict
|
| 283 |
+
|
| 284 |
+
self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/json.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import warnings
|
| 3 |
+
from collections import deque
|
| 4 |
+
from decimal import Decimal
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from re import Pattern
|
| 9 |
+
from types import GeneratorType
|
| 10 |
+
from typing import TYPE_CHECKING, Any, Callable, Union
|
| 11 |
+
from uuid import UUID
|
| 12 |
+
|
| 13 |
+
from typing_extensions import deprecated
|
| 14 |
+
|
| 15 |
+
from .._internal._import_utils import import_cached_base_model
|
| 16 |
+
from ..color import Color
|
| 17 |
+
from ..networks import NameEmail
|
| 18 |
+
from ..types import SecretBytes, SecretStr
|
| 19 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 20 |
+
|
| 21 |
+
if not TYPE_CHECKING:
|
| 22 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 23 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 24 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 25 |
+
|
| 26 |
+
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
|
| 30 |
+
return o.isoformat()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
|
| 34 |
+
"""Encodes a Decimal as int of there's no exponent, otherwise float.
|
| 35 |
+
|
| 36 |
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
| 37 |
+
where a integer (but not int typed) is used. Encoding this as a float
|
| 38 |
+
results in failed round-tripping between encode and parse.
|
| 39 |
+
Our Id type is a prime example of this.
|
| 40 |
+
|
| 41 |
+
>>> decimal_encoder(Decimal("1.0"))
|
| 42 |
+
1.0
|
| 43 |
+
|
| 44 |
+
>>> decimal_encoder(Decimal("1"))
|
| 45 |
+
1
|
| 46 |
+
"""
|
| 47 |
+
exponent = dec_value.as_tuple().exponent
|
| 48 |
+
if isinstance(exponent, int) and exponent >= 0:
|
| 49 |
+
return int(dec_value)
|
| 50 |
+
else:
|
| 51 |
+
return float(dec_value)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
|
| 55 |
+
bytes: lambda o: o.decode(),
|
| 56 |
+
Color: str,
|
| 57 |
+
datetime.date: isoformat,
|
| 58 |
+
datetime.datetime: isoformat,
|
| 59 |
+
datetime.time: isoformat,
|
| 60 |
+
datetime.timedelta: lambda td: td.total_seconds(),
|
| 61 |
+
Decimal: decimal_encoder,
|
| 62 |
+
Enum: lambda o: o.value,
|
| 63 |
+
frozenset: list,
|
| 64 |
+
deque: list,
|
| 65 |
+
GeneratorType: list,
|
| 66 |
+
IPv4Address: str,
|
| 67 |
+
IPv4Interface: str,
|
| 68 |
+
IPv4Network: str,
|
| 69 |
+
IPv6Address: str,
|
| 70 |
+
IPv6Interface: str,
|
| 71 |
+
IPv6Network: str,
|
| 72 |
+
NameEmail: str,
|
| 73 |
+
Path: str,
|
| 74 |
+
Pattern: lambda o: o.pattern,
|
| 75 |
+
SecretBytes: str,
|
| 76 |
+
SecretStr: str,
|
| 77 |
+
set: list,
|
| 78 |
+
UUID: str,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@deprecated(
|
| 83 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
| 84 |
+
category=None,
|
| 85 |
+
)
|
| 86 |
+
def pydantic_encoder(obj: Any) -> Any:
|
| 87 |
+
warnings.warn(
|
| 88 |
+
'`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
|
| 89 |
+
category=PydanticDeprecatedSince20,
|
| 90 |
+
stacklevel=2,
|
| 91 |
+
)
|
| 92 |
+
from dataclasses import asdict, is_dataclass
|
| 93 |
+
|
| 94 |
+
BaseModel = import_cached_base_model()
|
| 95 |
+
|
| 96 |
+
if isinstance(obj, BaseModel):
|
| 97 |
+
return obj.model_dump()
|
| 98 |
+
elif is_dataclass(obj):
|
| 99 |
+
return asdict(obj) # type: ignore
|
| 100 |
+
|
| 101 |
+
# Check the class type and its superclasses for a matching encoder
|
| 102 |
+
for base in obj.__class__.__mro__[:-1]:
|
| 103 |
+
try:
|
| 104 |
+
encoder = ENCODERS_BY_TYPE[base]
|
| 105 |
+
except KeyError:
|
| 106 |
+
continue
|
| 107 |
+
return encoder(obj)
|
| 108 |
+
else: # We have exited the for loop without finding a suitable encoder
|
| 109 |
+
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# TODO: Add a suggested migration path once there is a way to use custom encoders
|
| 113 |
+
@deprecated(
|
| 114 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
| 115 |
+
category=None,
|
| 116 |
+
)
|
| 117 |
+
def custom_pydantic_encoder(type_encoders: dict[Any, Callable[[type[Any]], Any]], obj: Any) -> Any:
|
| 118 |
+
warnings.warn(
|
| 119 |
+
'`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
|
| 120 |
+
category=PydanticDeprecatedSince20,
|
| 121 |
+
stacklevel=2,
|
| 122 |
+
)
|
| 123 |
+
# Check the class type and its superclasses for a matching encoder
|
| 124 |
+
for base in obj.__class__.__mro__[:-1]:
|
| 125 |
+
try:
|
| 126 |
+
encoder = type_encoders[base]
|
| 127 |
+
except KeyError:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
return encoder(obj)
|
| 131 |
+
else: # We have exited the for loop without finding a suitable encoder
|
| 132 |
+
return pydantic_encoder(obj)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@deprecated('`timedelta_isoformat` is deprecated.', category=None)
|
| 136 |
+
def timedelta_isoformat(td: datetime.timedelta) -> str:
|
| 137 |
+
"""ISO 8601 encoding for Python timedelta object."""
|
| 138 |
+
warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 139 |
+
minutes, seconds = divmod(td.seconds, 60)
|
| 140 |
+
hours, minutes = divmod(minutes, 60)
|
| 141 |
+
return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/parse.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import pickle
|
| 5 |
+
import warnings
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import TYPE_CHECKING, Any, Callable
|
| 9 |
+
|
| 10 |
+
from typing_extensions import deprecated
|
| 11 |
+
|
| 12 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 13 |
+
|
| 14 |
+
if not TYPE_CHECKING:
|
| 15 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 16 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 17 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Protocol(str, Enum):
|
| 21 |
+
json = 'json'
|
| 22 |
+
pickle = 'pickle'
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@deprecated('`load_str_bytes` is deprecated.', category=None)
|
| 26 |
+
def load_str_bytes(
|
| 27 |
+
b: str | bytes,
|
| 28 |
+
*,
|
| 29 |
+
content_type: str | None = None,
|
| 30 |
+
encoding: str = 'utf8',
|
| 31 |
+
proto: Protocol | None = None,
|
| 32 |
+
allow_pickle: bool = False,
|
| 33 |
+
json_loads: Callable[[str], Any] = json.loads,
|
| 34 |
+
) -> Any:
|
| 35 |
+
warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 36 |
+
if proto is None and content_type:
|
| 37 |
+
if content_type.endswith(('json', 'javascript')):
|
| 38 |
+
pass
|
| 39 |
+
elif allow_pickle and content_type.endswith('pickle'):
|
| 40 |
+
proto = Protocol.pickle
|
| 41 |
+
else:
|
| 42 |
+
raise TypeError(f'Unknown content-type: {content_type}')
|
| 43 |
+
|
| 44 |
+
proto = proto or Protocol.json
|
| 45 |
+
|
| 46 |
+
if proto == Protocol.json:
|
| 47 |
+
if isinstance(b, bytes):
|
| 48 |
+
b = b.decode(encoding)
|
| 49 |
+
return json_loads(b) # type: ignore
|
| 50 |
+
elif proto == Protocol.pickle:
|
| 51 |
+
if not allow_pickle:
|
| 52 |
+
raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
|
| 53 |
+
bb = b if isinstance(b, bytes) else b.encode() # type: ignore
|
| 54 |
+
return pickle.loads(bb)
|
| 55 |
+
else:
|
| 56 |
+
raise TypeError(f'Unknown protocol: {proto}')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@deprecated('`load_file` is deprecated.', category=None)
|
| 60 |
+
def load_file(
|
| 61 |
+
path: str | Path,
|
| 62 |
+
*,
|
| 63 |
+
content_type: str | None = None,
|
| 64 |
+
encoding: str = 'utf8',
|
| 65 |
+
proto: Protocol | None = None,
|
| 66 |
+
allow_pickle: bool = False,
|
| 67 |
+
json_loads: Callable[[str], Any] = json.loads,
|
| 68 |
+
) -> Any:
|
| 69 |
+
warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
|
| 70 |
+
path = Path(path)
|
| 71 |
+
b = path.read_bytes()
|
| 72 |
+
if content_type is None:
|
| 73 |
+
if path.suffix in ('.js', '.json'):
|
| 74 |
+
proto = Protocol.json
|
| 75 |
+
elif path.suffix == '.pkl':
|
| 76 |
+
proto = Protocol.pickle
|
| 77 |
+
|
| 78 |
+
return load_str_bytes(
|
| 79 |
+
b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
|
| 80 |
+
)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/deprecated/tools.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
|
| 6 |
+
|
| 7 |
+
from typing_extensions import deprecated
|
| 8 |
+
|
| 9 |
+
from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema
|
| 10 |
+
from ..type_adapter import TypeAdapter
|
| 11 |
+
from ..warnings import PydanticDeprecatedSince20
|
| 12 |
+
|
| 13 |
+
if not TYPE_CHECKING:
|
| 14 |
+
# See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
|
| 15 |
+
# and https://youtrack.jetbrains.com/issue/PY-51428
|
| 16 |
+
DeprecationWarning = PydanticDeprecatedSince20
|
| 17 |
+
|
| 18 |
+
__all__ = 'parse_obj_as', 'schema_of', 'schema_json_of'
|
| 19 |
+
|
| 20 |
+
NameFactory = Union[str, Callable[[type[Any]], str]]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
T = TypeVar('T')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@deprecated(
|
| 27 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
| 28 |
+
category=None,
|
| 29 |
+
)
|
| 30 |
+
def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T:
|
| 31 |
+
warnings.warn(
|
| 32 |
+
'`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
|
| 33 |
+
category=PydanticDeprecatedSince20,
|
| 34 |
+
stacklevel=2,
|
| 35 |
+
)
|
| 36 |
+
if type_name is not None: # pragma: no cover
|
| 37 |
+
warnings.warn(
|
| 38 |
+
'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models',
|
| 39 |
+
DeprecationWarning,
|
| 40 |
+
stacklevel=2,
|
| 41 |
+
)
|
| 42 |
+
return TypeAdapter(type_).validate_python(obj)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@deprecated(
|
| 46 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 47 |
+
category=None,
|
| 48 |
+
)
|
| 49 |
+
def schema_of(
|
| 50 |
+
type_: Any,
|
| 51 |
+
*,
|
| 52 |
+
title: NameFactory | None = None,
|
| 53 |
+
by_alias: bool = True,
|
| 54 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 55 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
| 56 |
+
) -> dict[str, Any]:
|
| 57 |
+
"""Generate a JSON schema (as dict) for the passed model or dynamically generated one."""
|
| 58 |
+
warnings.warn(
|
| 59 |
+
'`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 60 |
+
category=PydanticDeprecatedSince20,
|
| 61 |
+
stacklevel=2,
|
| 62 |
+
)
|
| 63 |
+
res = TypeAdapter(type_).json_schema(
|
| 64 |
+
by_alias=by_alias,
|
| 65 |
+
schema_generator=schema_generator,
|
| 66 |
+
ref_template=ref_template,
|
| 67 |
+
)
|
| 68 |
+
if title is not None:
|
| 69 |
+
if isinstance(title, str):
|
| 70 |
+
res['title'] = title
|
| 71 |
+
else:
|
| 72 |
+
warnings.warn(
|
| 73 |
+
'Passing a callable for the `title` parameter is deprecated and no longer supported',
|
| 74 |
+
DeprecationWarning,
|
| 75 |
+
stacklevel=2,
|
| 76 |
+
)
|
| 77 |
+
res['title'] = title(type_)
|
| 78 |
+
return res
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@deprecated(
|
| 82 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 83 |
+
category=None,
|
| 84 |
+
)
|
| 85 |
+
def schema_json_of(
|
| 86 |
+
type_: Any,
|
| 87 |
+
*,
|
| 88 |
+
title: NameFactory | None = None,
|
| 89 |
+
by_alias: bool = True,
|
| 90 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 91 |
+
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
|
| 92 |
+
**dumps_kwargs: Any,
|
| 93 |
+
) -> str:
|
| 94 |
+
"""Generate a JSON schema (as JSON) for the passed model or dynamically generated one."""
|
| 95 |
+
warnings.warn(
|
| 96 |
+
'`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
|
| 97 |
+
category=PydanticDeprecatedSince20,
|
| 98 |
+
stacklevel=2,
|
| 99 |
+
)
|
| 100 |
+
return json.dumps(
|
| 101 |
+
schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator),
|
| 102 |
+
**dumps_kwargs,
|
| 103 |
+
)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""The "experimental" module of pydantic contains potential new features that are subject to change."""
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/arguments_schema.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental module exposing a function to generate a core schema that validates callable arguments."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from typing import Any, Literal
|
| 7 |
+
|
| 8 |
+
from pydantic_core import CoreSchema
|
| 9 |
+
|
| 10 |
+
from pydantic import ConfigDict
|
| 11 |
+
from pydantic._internal import _config, _generate_schema, _namespace_utils
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_arguments_schema(
|
| 15 |
+
func: Callable[..., Any],
|
| 16 |
+
schema_type: Literal['arguments', 'arguments-v3'] = 'arguments-v3',
|
| 17 |
+
parameters_callback: Callable[[int, str, Any], Literal['skip'] | None] | None = None,
|
| 18 |
+
config: ConfigDict | None = None,
|
| 19 |
+
) -> CoreSchema:
|
| 20 |
+
"""Generate the schema for the arguments of a function.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
func: The function to generate the schema for.
|
| 24 |
+
schema_type: The type of schema to generate.
|
| 25 |
+
parameters_callback: A callable that will be invoked for each parameter. The callback
|
| 26 |
+
should take three required arguments: the index, the name and the type annotation
|
| 27 |
+
(or [`Parameter.empty`][inspect.Parameter.empty] if not annotated) of the parameter.
|
| 28 |
+
The callback can optionally return `'skip'`, so that the parameter gets excluded
|
| 29 |
+
from the resulting schema.
|
| 30 |
+
config: The configuration to use.
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
The generated schema.
|
| 34 |
+
"""
|
| 35 |
+
generate_schema = _generate_schema.GenerateSchema(
|
| 36 |
+
_config.ConfigWrapper(config),
|
| 37 |
+
ns_resolver=_namespace_utils.NsResolver(namespaces_tuple=_namespace_utils.ns_for_function(func)),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
if schema_type == 'arguments':
|
| 41 |
+
schema = generate_schema._arguments_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
|
| 42 |
+
else:
|
| 43 |
+
schema = generate_schema._arguments_v3_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
|
| 44 |
+
return generate_schema.clean_schema(schema)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/missing_sentinel.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental module exposing a function a `MISSING` sentinel."""
|
| 2 |
+
|
| 3 |
+
from pydantic_core import MISSING
|
| 4 |
+
|
| 5 |
+
__all__ = ('MISSING',)
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/experimental/pipeline.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental pipeline API functionality. Be careful with this API, it's subject to change."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import datetime
|
| 6 |
+
import operator
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
from collections import deque
|
| 10 |
+
from collections.abc import Container
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from decimal import Decimal
|
| 13 |
+
from functools import cached_property, partial
|
| 14 |
+
from re import Pattern
|
| 15 |
+
from typing import TYPE_CHECKING, Annotated, Any, Callable, Generic, Protocol, TypeVar, Union, overload
|
| 16 |
+
|
| 17 |
+
import annotated_types
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from pydantic import GetCoreSchemaHandler
|
| 21 |
+
|
| 22 |
+
from pydantic_core import PydanticCustomError
|
| 23 |
+
from pydantic_core import core_schema as cs
|
| 24 |
+
|
| 25 |
+
from pydantic import Strict
|
| 26 |
+
from pydantic._internal._internal_dataclass import slots_true as _slots_true
|
| 27 |
+
|
| 28 |
+
if sys.version_info < (3, 10):
|
| 29 |
+
EllipsisType = type(Ellipsis)
|
| 30 |
+
else:
|
| 31 |
+
from types import EllipsisType
|
| 32 |
+
|
| 33 |
+
__all__ = ['validate_as', 'validate_as_deferred', 'transform']
|
| 34 |
+
|
| 35 |
+
_slots_frozen = {**_slots_true, 'frozen': True}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass(**_slots_frozen)
|
| 39 |
+
class _ValidateAs:
|
| 40 |
+
tp: type[Any]
|
| 41 |
+
strict: bool = False
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass
|
| 45 |
+
class _ValidateAsDefer:
|
| 46 |
+
func: Callable[[], type[Any]]
|
| 47 |
+
|
| 48 |
+
@cached_property
|
| 49 |
+
def tp(self) -> type[Any]:
|
| 50 |
+
return self.func()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass(**_slots_frozen)
|
| 54 |
+
class _Transform:
|
| 55 |
+
func: Callable[[Any], Any]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(**_slots_frozen)
|
| 59 |
+
class _PipelineOr:
|
| 60 |
+
left: _Pipeline[Any, Any]
|
| 61 |
+
right: _Pipeline[Any, Any]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass(**_slots_frozen)
|
| 65 |
+
class _PipelineAnd:
|
| 66 |
+
left: _Pipeline[Any, Any]
|
| 67 |
+
right: _Pipeline[Any, Any]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(**_slots_frozen)
|
| 71 |
+
class _Eq:
|
| 72 |
+
value: Any
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass(**_slots_frozen)
|
| 76 |
+
class _NotEq:
|
| 77 |
+
value: Any
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(**_slots_frozen)
|
| 81 |
+
class _In:
|
| 82 |
+
values: Container[Any]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@dataclass(**_slots_frozen)
|
| 86 |
+
class _NotIn:
|
| 87 |
+
values: Container[Any]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_ConstraintAnnotation = Union[
|
| 91 |
+
annotated_types.Le,
|
| 92 |
+
annotated_types.Ge,
|
| 93 |
+
annotated_types.Lt,
|
| 94 |
+
annotated_types.Gt,
|
| 95 |
+
annotated_types.Len,
|
| 96 |
+
annotated_types.MultipleOf,
|
| 97 |
+
annotated_types.Timezone,
|
| 98 |
+
annotated_types.Interval,
|
| 99 |
+
annotated_types.Predicate,
|
| 100 |
+
# common predicates not included in annotated_types
|
| 101 |
+
_Eq,
|
| 102 |
+
_NotEq,
|
| 103 |
+
_In,
|
| 104 |
+
_NotIn,
|
| 105 |
+
# regular expressions
|
| 106 |
+
Pattern[str],
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclass(**_slots_frozen)
|
| 111 |
+
class _Constraint:
|
| 112 |
+
constraint: _ConstraintAnnotation
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
_Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint]
|
| 116 |
+
|
| 117 |
+
_InT = TypeVar('_InT')
|
| 118 |
+
_OutT = TypeVar('_OutT')
|
| 119 |
+
_NewOutT = TypeVar('_NewOutT')
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class _FieldTypeMarker:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626
|
| 127 |
+
# Also, make this frozen eventually, but that doesn't work right now because of the generic base
|
| 128 |
+
# Which attempts to modify __orig_base__ and such.
|
| 129 |
+
# We could go with a manual freeze, but that seems overkill for now.
|
| 130 |
+
@dataclass(**_slots_true)
|
| 131 |
+
class _Pipeline(Generic[_InT, _OutT]):
|
| 132 |
+
"""Abstract representation of a chain of validation, transformation, and parsing steps."""
|
| 133 |
+
|
| 134 |
+
_steps: tuple[_Step, ...]
|
| 135 |
+
|
| 136 |
+
def transform(
|
| 137 |
+
self,
|
| 138 |
+
func: Callable[[_OutT], _NewOutT],
|
| 139 |
+
) -> _Pipeline[_InT, _NewOutT]:
|
| 140 |
+
"""Transform the output of the previous step.
|
| 141 |
+
|
| 142 |
+
If used as the first step in a pipeline, the type of the field is used.
|
| 143 |
+
That is, the transformation is applied to after the value is parsed to the field's type.
|
| 144 |
+
"""
|
| 145 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))
|
| 146 |
+
|
| 147 |
+
@overload
|
| 148 |
+
def validate_as(self, tp: type[_NewOutT], *, strict: bool = ...) -> _Pipeline[_InT, _NewOutT]: ...
|
| 149 |
+
|
| 150 |
+
@overload
|
| 151 |
+
def validate_as(self, tp: EllipsisType, *, strict: bool = ...) -> _Pipeline[_InT, Any]: # type: ignore
|
| 152 |
+
...
|
| 153 |
+
|
| 154 |
+
def validate_as(self, tp: type[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore
|
| 155 |
+
"""Validate / parse the input into a new type.
|
| 156 |
+
|
| 157 |
+
If no type is provided, the type of the field is used.
|
| 158 |
+
|
| 159 |
+
Types are parsed in Pydantic's `lax` mode by default,
|
| 160 |
+
but you can enable `strict` mode by passing `strict=True`.
|
| 161 |
+
"""
|
| 162 |
+
if isinstance(tp, EllipsisType):
|
| 163 |
+
return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),))
|
| 164 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))
|
| 165 |
+
|
| 166 |
+
def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]:
|
| 167 |
+
"""Parse the input into a new type, deferring resolution of the type until the current class
|
| 168 |
+
is fully defined.
|
| 169 |
+
|
| 170 |
+
This is useful when you need to reference the class in it's own type annotations.
|
| 171 |
+
"""
|
| 172 |
+
return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))
|
| 173 |
+
|
| 174 |
+
# constraints
|
| 175 |
+
@overload
|
| 176 |
+
def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ...
|
| 177 |
+
|
| 178 |
+
@overload
|
| 179 |
+
def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ...
|
| 180 |
+
|
| 181 |
+
@overload
|
| 182 |
+
def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ...
|
| 183 |
+
|
| 184 |
+
@overload
|
| 185 |
+
def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ...
|
| 186 |
+
|
| 187 |
+
@overload
|
| 188 |
+
def constrain(
|
| 189 |
+
self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len
|
| 190 |
+
) -> _Pipeline[_InT, _NewOutLen]: ...
|
| 191 |
+
|
| 192 |
+
@overload
|
| 193 |
+
def constrain(
|
| 194 |
+
self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf
|
| 195 |
+
) -> _Pipeline[_InT, _NewOutT]: ...
|
| 196 |
+
|
| 197 |
+
@overload
|
| 198 |
+
def constrain(
|
| 199 |
+
self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone
|
| 200 |
+
) -> _Pipeline[_InT, _NewOutDatetime]: ...
|
| 201 |
+
|
| 202 |
+
@overload
|
| 203 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ...
|
| 204 |
+
|
| 205 |
+
@overload
|
| 206 |
+
def constrain(
|
| 207 |
+
self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval
|
| 208 |
+
) -> _Pipeline[_InT, _NewOutInterval]: ...
|
| 209 |
+
|
| 210 |
+
@overload
|
| 211 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ...
|
| 212 |
+
|
| 213 |
+
@overload
|
| 214 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ...
|
| 215 |
+
|
| 216 |
+
@overload
|
| 217 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ...
|
| 218 |
+
|
| 219 |
+
@overload
|
| 220 |
+
def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ...
|
| 221 |
+
|
| 222 |
+
@overload
|
| 223 |
+
def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ...
|
| 224 |
+
|
| 225 |
+
def constrain(self, constraint: _ConstraintAnnotation) -> Any:
|
| 226 |
+
"""Constrain a value to meet a certain condition.
|
| 227 |
+
|
| 228 |
+
We support most conditions from `annotated_types`, as well as regular expressions.
|
| 229 |
+
|
| 230 |
+
Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc
|
| 231 |
+
so you don't need to call this directly.
|
| 232 |
+
"""
|
| 233 |
+
return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))
|
| 234 |
+
|
| 235 |
+
def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]:
|
| 236 |
+
"""Constrain a value to meet a certain predicate."""
|
| 237 |
+
return self.constrain(annotated_types.Predicate(func))
|
| 238 |
+
|
| 239 |
+
def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]:
|
| 240 |
+
"""Constrain a value to be greater than a certain value."""
|
| 241 |
+
return self.constrain(annotated_types.Gt(gt))
|
| 242 |
+
|
| 243 |
+
def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]:
|
| 244 |
+
"""Constrain a value to be less than a certain value."""
|
| 245 |
+
return self.constrain(annotated_types.Lt(lt))
|
| 246 |
+
|
| 247 |
+
def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]:
|
| 248 |
+
"""Constrain a value to be greater than or equal to a certain value."""
|
| 249 |
+
return self.constrain(annotated_types.Ge(ge))
|
| 250 |
+
|
| 251 |
+
def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]:
|
| 252 |
+
"""Constrain a value to be less than or equal to a certain value."""
|
| 253 |
+
return self.constrain(annotated_types.Le(le))
|
| 254 |
+
|
| 255 |
+
def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]:
|
| 256 |
+
"""Constrain a value to have a certain length."""
|
| 257 |
+
return self.constrain(annotated_types.Len(min_len, max_len))
|
| 258 |
+
|
| 259 |
+
@overload
|
| 260 |
+
def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ...
|
| 261 |
+
|
| 262 |
+
@overload
|
| 263 |
+
def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ...
|
| 264 |
+
|
| 265 |
+
def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]:
|
| 266 |
+
"""Constrain a value to be a multiple of a certain number."""
|
| 267 |
+
return self.constrain(annotated_types.MultipleOf(multiple_of))
|
| 268 |
+
|
| 269 |
+
def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
|
| 270 |
+
"""Constrain a value to be equal to a certain value."""
|
| 271 |
+
return self.constrain(_Eq(value))
|
| 272 |
+
|
| 273 |
+
def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
|
| 274 |
+
"""Constrain a value to not be equal to a certain value."""
|
| 275 |
+
return self.constrain(_NotEq(value))
|
| 276 |
+
|
| 277 |
+
def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
|
| 278 |
+
"""Constrain a value to be in a certain set."""
|
| 279 |
+
return self.constrain(_In(values))
|
| 280 |
+
|
| 281 |
+
def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
|
| 282 |
+
"""Constrain a value to not be in a certain set."""
|
| 283 |
+
return self.constrain(_NotIn(values))
|
| 284 |
+
|
| 285 |
+
# timezone methods
|
| 286 |
+
def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
|
| 287 |
+
return self.constrain(annotated_types.Timezone(None))
|
| 288 |
+
|
| 289 |
+
def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
|
| 290 |
+
return self.constrain(annotated_types.Timezone(...))
|
| 291 |
+
|
| 292 |
+
def datetime_tz(
|
| 293 |
+
self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo
|
| 294 |
+
) -> _Pipeline[_InT, datetime.datetime]:
|
| 295 |
+
return self.constrain(annotated_types.Timezone(tz)) # type: ignore
|
| 296 |
+
|
| 297 |
+
def datetime_with_tz(
|
| 298 |
+
self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None
|
| 299 |
+
) -> _Pipeline[_InT, datetime.datetime]:
|
| 300 |
+
return self.transform(partial(datetime.datetime.replace, tzinfo=tz))
|
| 301 |
+
|
| 302 |
+
# string methods
|
| 303 |
+
def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 304 |
+
return self.transform(str.lower)
|
| 305 |
+
|
| 306 |
+
def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 307 |
+
return self.transform(str.upper)
|
| 308 |
+
|
| 309 |
+
def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 310 |
+
return self.transform(str.title)
|
| 311 |
+
|
| 312 |
+
def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
|
| 313 |
+
return self.transform(str.strip)
|
| 314 |
+
|
| 315 |
+
def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]:
|
| 316 |
+
return self.constrain(re.compile(pattern))
|
| 317 |
+
|
| 318 |
+
def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]:
|
| 319 |
+
return self.predicate(lambda v: substring in v)
|
| 320 |
+
|
| 321 |
+
def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]:
|
| 322 |
+
return self.predicate(lambda v: v.startswith(prefix))
|
| 323 |
+
|
| 324 |
+
def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]:
|
| 325 |
+
return self.predicate(lambda v: v.endswith(suffix))
|
| 326 |
+
|
| 327 |
+
# operators
|
| 328 |
+
def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]:
|
| 329 |
+
"""Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails."""
|
| 330 |
+
return _Pipeline((_PipelineOr(self, other),))
|
| 331 |
+
|
| 332 |
+
__or__ = otherwise
|
| 333 |
+
|
| 334 |
+
def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]:
|
| 335 |
+
"""Pipe the result of one validation chain into another."""
|
| 336 |
+
return _Pipeline((_PipelineAnd(self, other),))
|
| 337 |
+
|
| 338 |
+
__and__ = then
|
| 339 |
+
|
| 340 |
+
def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema:
|
| 341 |
+
queue = deque(self._steps)
|
| 342 |
+
|
| 343 |
+
s = None
|
| 344 |
+
|
| 345 |
+
while queue:
|
| 346 |
+
step = queue.popleft()
|
| 347 |
+
s = _apply_step(step, s, handler, source_type)
|
| 348 |
+
|
| 349 |
+
s = s or cs.any_schema()
|
| 350 |
+
return s
|
| 351 |
+
|
| 352 |
+
def __supports_type__(self, _: _OutT) -> bool:
|
| 353 |
+
raise NotImplementedError
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
validate_as = _Pipeline[Any, Any](()).validate_as
|
| 357 |
+
validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred
|
| 358 |
+
transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _check_func(
|
| 362 |
+
func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None
|
| 363 |
+
) -> cs.CoreSchema:
|
| 364 |
+
def handler(v: Any) -> Any:
|
| 365 |
+
if func(v):
|
| 366 |
+
return v
|
| 367 |
+
raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}')
|
| 368 |
+
|
| 369 |
+
if s is None:
|
| 370 |
+
return cs.no_info_plain_validator_function(handler)
|
| 371 |
+
else:
|
| 372 |
+
return cs.no_info_after_validator_function(handler, s)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
|
| 376 |
+
if isinstance(step, _ValidateAs):
|
| 377 |
+
s = _apply_parse(s, step.tp, step.strict, handler, source_type)
|
| 378 |
+
elif isinstance(step, _ValidateAsDefer):
|
| 379 |
+
s = _apply_parse(s, step.tp, False, handler, source_type)
|
| 380 |
+
elif isinstance(step, _Transform):
|
| 381 |
+
s = _apply_transform(s, step.func, handler)
|
| 382 |
+
elif isinstance(step, _Constraint):
|
| 383 |
+
s = _apply_constraint(s, step.constraint)
|
| 384 |
+
elif isinstance(step, _PipelineOr):
|
| 385 |
+
s = cs.union_schema([handler(step.left), handler(step.right)])
|
| 386 |
+
else:
|
| 387 |
+
assert isinstance(step, _PipelineAnd)
|
| 388 |
+
s = cs.chain_schema([handler(step.left), handler(step.right)])
|
| 389 |
+
return s
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _apply_parse(
|
| 393 |
+
s: cs.CoreSchema | None,
|
| 394 |
+
tp: type[Any],
|
| 395 |
+
strict: bool,
|
| 396 |
+
handler: GetCoreSchemaHandler,
|
| 397 |
+
source_type: Any,
|
| 398 |
+
) -> cs.CoreSchema:
|
| 399 |
+
if tp is _FieldTypeMarker:
|
| 400 |
+
return cs.chain_schema([s, handler(source_type)]) if s else handler(source_type)
|
| 401 |
+
|
| 402 |
+
if strict:
|
| 403 |
+
tp = Annotated[tp, Strict()] # type: ignore
|
| 404 |
+
|
| 405 |
+
if s and s['type'] == 'any':
|
| 406 |
+
return handler(tp)
|
| 407 |
+
else:
|
| 408 |
+
return cs.chain_schema([s, handler(tp)]) if s else handler(tp)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _apply_transform(
|
| 412 |
+
s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler
|
| 413 |
+
) -> cs.CoreSchema:
|
| 414 |
+
if s is None:
|
| 415 |
+
return cs.no_info_plain_validator_function(func)
|
| 416 |
+
|
| 417 |
+
if s['type'] == 'str':
|
| 418 |
+
if func is str.strip:
|
| 419 |
+
s = s.copy()
|
| 420 |
+
s['strip_whitespace'] = True
|
| 421 |
+
return s
|
| 422 |
+
elif func is str.lower:
|
| 423 |
+
s = s.copy()
|
| 424 |
+
s['to_lower'] = True
|
| 425 |
+
return s
|
| 426 |
+
elif func is str.upper:
|
| 427 |
+
s = s.copy()
|
| 428 |
+
s['to_upper'] = True
|
| 429 |
+
return s
|
| 430 |
+
|
| 431 |
+
return cs.no_info_after_validator_function(func, s)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _apply_constraint( # noqa: C901
|
| 435 |
+
s: cs.CoreSchema | None, constraint: _ConstraintAnnotation
|
| 436 |
+
) -> cs.CoreSchema:
|
| 437 |
+
"""Apply a single constraint to a schema."""
|
| 438 |
+
if isinstance(constraint, annotated_types.Gt):
|
| 439 |
+
gt = constraint.gt
|
| 440 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 441 |
+
s = s.copy()
|
| 442 |
+
if s['type'] == 'int' and isinstance(gt, int):
|
| 443 |
+
s['gt'] = gt
|
| 444 |
+
elif s['type'] == 'float' and isinstance(gt, float):
|
| 445 |
+
s['gt'] = gt
|
| 446 |
+
elif s['type'] == 'decimal' and isinstance(gt, Decimal):
|
| 447 |
+
s['gt'] = gt
|
| 448 |
+
else:
|
| 449 |
+
|
| 450 |
+
def check_gt(v: Any) -> bool:
|
| 451 |
+
return v > gt
|
| 452 |
+
|
| 453 |
+
s = _check_func(check_gt, f'> {gt}', s)
|
| 454 |
+
elif isinstance(constraint, annotated_types.Ge):
|
| 455 |
+
ge = constraint.ge
|
| 456 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 457 |
+
s = s.copy()
|
| 458 |
+
if s['type'] == 'int' and isinstance(ge, int):
|
| 459 |
+
s['ge'] = ge
|
| 460 |
+
elif s['type'] == 'float' and isinstance(ge, float):
|
| 461 |
+
s['ge'] = ge
|
| 462 |
+
elif s['type'] == 'decimal' and isinstance(ge, Decimal):
|
| 463 |
+
s['ge'] = ge
|
| 464 |
+
|
| 465 |
+
def check_ge(v: Any) -> bool:
|
| 466 |
+
return v >= ge
|
| 467 |
+
|
| 468 |
+
s = _check_func(check_ge, f'>= {ge}', s)
|
| 469 |
+
elif isinstance(constraint, annotated_types.Lt):
|
| 470 |
+
lt = constraint.lt
|
| 471 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 472 |
+
s = s.copy()
|
| 473 |
+
if s['type'] == 'int' and isinstance(lt, int):
|
| 474 |
+
s['lt'] = lt
|
| 475 |
+
elif s['type'] == 'float' and isinstance(lt, float):
|
| 476 |
+
s['lt'] = lt
|
| 477 |
+
elif s['type'] == 'decimal' and isinstance(lt, Decimal):
|
| 478 |
+
s['lt'] = lt
|
| 479 |
+
|
| 480 |
+
def check_lt(v: Any) -> bool:
|
| 481 |
+
return v < lt
|
| 482 |
+
|
| 483 |
+
s = _check_func(check_lt, f'< {lt}', s)
|
| 484 |
+
elif isinstance(constraint, annotated_types.Le):
|
| 485 |
+
le = constraint.le
|
| 486 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 487 |
+
s = s.copy()
|
| 488 |
+
if s['type'] == 'int' and isinstance(le, int):
|
| 489 |
+
s['le'] = le
|
| 490 |
+
elif s['type'] == 'float' and isinstance(le, float):
|
| 491 |
+
s['le'] = le
|
| 492 |
+
elif s['type'] == 'decimal' and isinstance(le, Decimal):
|
| 493 |
+
s['le'] = le
|
| 494 |
+
|
| 495 |
+
def check_le(v: Any) -> bool:
|
| 496 |
+
return v <= le
|
| 497 |
+
|
| 498 |
+
s = _check_func(check_le, f'<= {le}', s)
|
| 499 |
+
elif isinstance(constraint, annotated_types.Len):
|
| 500 |
+
min_len = constraint.min_length
|
| 501 |
+
max_len = constraint.max_length
|
| 502 |
+
|
| 503 |
+
if s and s['type'] in {'str', 'list', 'tuple', 'set', 'frozenset', 'dict'}:
|
| 504 |
+
assert (
|
| 505 |
+
s['type'] == 'str'
|
| 506 |
+
or s['type'] == 'list'
|
| 507 |
+
or s['type'] == 'tuple'
|
| 508 |
+
or s['type'] == 'set'
|
| 509 |
+
or s['type'] == 'dict'
|
| 510 |
+
or s['type'] == 'frozenset'
|
| 511 |
+
)
|
| 512 |
+
s = s.copy()
|
| 513 |
+
if min_len != 0:
|
| 514 |
+
s['min_length'] = min_len
|
| 515 |
+
if max_len is not None:
|
| 516 |
+
s['max_length'] = max_len
|
| 517 |
+
|
| 518 |
+
def check_len(v: Any) -> bool:
|
| 519 |
+
if max_len is not None:
|
| 520 |
+
return (min_len <= len(v)) and (len(v) <= max_len)
|
| 521 |
+
return min_len <= len(v)
|
| 522 |
+
|
| 523 |
+
s = _check_func(check_len, f'length >= {min_len} and length <= {max_len}', s)
|
| 524 |
+
elif isinstance(constraint, annotated_types.MultipleOf):
|
| 525 |
+
multiple_of = constraint.multiple_of
|
| 526 |
+
if s and s['type'] in {'int', 'float', 'decimal'}:
|
| 527 |
+
s = s.copy()
|
| 528 |
+
if s['type'] == 'int' and isinstance(multiple_of, int):
|
| 529 |
+
s['multiple_of'] = multiple_of
|
| 530 |
+
elif s['type'] == 'float' and isinstance(multiple_of, float):
|
| 531 |
+
s['multiple_of'] = multiple_of
|
| 532 |
+
elif s['type'] == 'decimal' and isinstance(multiple_of, Decimal):
|
| 533 |
+
s['multiple_of'] = multiple_of
|
| 534 |
+
|
| 535 |
+
def check_multiple_of(v: Any) -> bool:
|
| 536 |
+
return v % multiple_of == 0
|
| 537 |
+
|
| 538 |
+
s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)
|
| 539 |
+
elif isinstance(constraint, annotated_types.Timezone):
|
| 540 |
+
tz = constraint.tz
|
| 541 |
+
|
| 542 |
+
if tz is ...:
|
| 543 |
+
if s and s['type'] == 'datetime':
|
| 544 |
+
s = s.copy()
|
| 545 |
+
s['tz_constraint'] = 'aware'
|
| 546 |
+
else:
|
| 547 |
+
|
| 548 |
+
def check_tz_aware(v: object) -> bool:
|
| 549 |
+
assert isinstance(v, datetime.datetime)
|
| 550 |
+
return v.tzinfo is not None
|
| 551 |
+
|
| 552 |
+
s = _check_func(check_tz_aware, 'timezone aware', s)
|
| 553 |
+
elif tz is None:
|
| 554 |
+
if s and s['type'] == 'datetime':
|
| 555 |
+
s = s.copy()
|
| 556 |
+
s['tz_constraint'] = 'naive'
|
| 557 |
+
else:
|
| 558 |
+
|
| 559 |
+
def check_tz_naive(v: object) -> bool:
|
| 560 |
+
assert isinstance(v, datetime.datetime)
|
| 561 |
+
return v.tzinfo is None
|
| 562 |
+
|
| 563 |
+
s = _check_func(check_tz_naive, 'timezone naive', s)
|
| 564 |
+
else:
|
| 565 |
+
raise NotImplementedError('Constraining to a specific timezone is not yet supported')
|
| 566 |
+
elif isinstance(constraint, annotated_types.Interval):
|
| 567 |
+
if constraint.ge:
|
| 568 |
+
s = _apply_constraint(s, annotated_types.Ge(constraint.ge))
|
| 569 |
+
if constraint.gt:
|
| 570 |
+
s = _apply_constraint(s, annotated_types.Gt(constraint.gt))
|
| 571 |
+
if constraint.le:
|
| 572 |
+
s = _apply_constraint(s, annotated_types.Le(constraint.le))
|
| 573 |
+
if constraint.lt:
|
| 574 |
+
s = _apply_constraint(s, annotated_types.Lt(constraint.lt))
|
| 575 |
+
assert s is not None
|
| 576 |
+
elif isinstance(constraint, annotated_types.Predicate):
|
| 577 |
+
func = constraint.func
|
| 578 |
+
# Same logic as in `_known_annotated_metadata.apply_known_metadata()`:
|
| 579 |
+
predicate_name = f'{func.__qualname__!r} ' if hasattr(func, '__qualname__') else ''
|
| 580 |
+
|
| 581 |
+
def predicate_func(v: Any) -> Any:
|
| 582 |
+
if not func(v):
|
| 583 |
+
raise PydanticCustomError(
|
| 584 |
+
'predicate_failed',
|
| 585 |
+
f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType]
|
| 586 |
+
)
|
| 587 |
+
return v
|
| 588 |
+
|
| 589 |
+
if s is None:
|
| 590 |
+
s = cs.no_info_plain_validator_function(predicate_func)
|
| 591 |
+
else:
|
| 592 |
+
s = cs.no_info_after_validator_function(predicate_func, s)
|
| 593 |
+
elif isinstance(constraint, _NotEq):
|
| 594 |
+
value = constraint.value
|
| 595 |
+
|
| 596 |
+
def check_not_eq(v: Any) -> bool:
|
| 597 |
+
return operator.__ne__(v, value)
|
| 598 |
+
|
| 599 |
+
s = _check_func(check_not_eq, f'!= {value}', s)
|
| 600 |
+
elif isinstance(constraint, _Eq):
|
| 601 |
+
value = constraint.value
|
| 602 |
+
|
| 603 |
+
def check_eq(v: Any) -> bool:
|
| 604 |
+
return operator.__eq__(v, value)
|
| 605 |
+
|
| 606 |
+
s = _check_func(check_eq, f'== {value}', s)
|
| 607 |
+
elif isinstance(constraint, _In):
|
| 608 |
+
values = constraint.values
|
| 609 |
+
|
| 610 |
+
def check_in(v: Any) -> bool:
|
| 611 |
+
return operator.__contains__(values, v)
|
| 612 |
+
|
| 613 |
+
s = _check_func(check_in, f'in {values}', s)
|
| 614 |
+
elif isinstance(constraint, _NotIn):
|
| 615 |
+
values = constraint.values
|
| 616 |
+
|
| 617 |
+
def check_not_in(v: Any) -> bool:
|
| 618 |
+
return operator.__not__(operator.__contains__(values, v))
|
| 619 |
+
|
| 620 |
+
s = _check_func(check_not_in, f'not in {values}', s)
|
| 621 |
+
else:
|
| 622 |
+
assert isinstance(constraint, Pattern)
|
| 623 |
+
if s and s['type'] == 'str':
|
| 624 |
+
s = s.copy()
|
| 625 |
+
s['pattern'] = constraint.pattern
|
| 626 |
+
else:
|
| 627 |
+
|
| 628 |
+
def check_pattern(v: object) -> bool:
|
| 629 |
+
assert isinstance(v, str)
|
| 630 |
+
return constraint.match(v) is not None
|
| 631 |
+
|
| 632 |
+
s = _check_func(check_pattern, f'~ {constraint.pattern}', s)
|
| 633 |
+
return s
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol):
|
| 637 |
+
pass
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
class _SupportsLen(Protocol):
|
| 641 |
+
def __len__(self) -> int: ...
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
_NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt)
|
| 645 |
+
_NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe)
|
| 646 |
+
_NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt)
|
| 647 |
+
_NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe)
|
| 648 |
+
_NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen)
|
| 649 |
+
_NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv)
|
| 650 |
+
_NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod)
|
| 651 |
+
_NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime)
|
| 652 |
+
_NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange)
|
| 653 |
+
_OtherIn = TypeVar('_OtherIn')
|
| 654 |
+
_OtherOut = TypeVar('_OtherOut')
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/plugin/__init__.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""!!! abstract "Usage Documentation"
|
| 2 |
+
[Build a Plugin](../concepts/plugins.md#build-a-plugin)
|
| 3 |
+
|
| 4 |
+
Plugin interface for Pydantic plugins, and related types.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from typing import Any, Callable, Literal, NamedTuple
|
| 10 |
+
|
| 11 |
+
from pydantic_core import CoreConfig, CoreSchema, ValidationError
|
| 12 |
+
from typing_extensions import Protocol, TypeAlias
|
| 13 |
+
|
| 14 |
+
from pydantic.config import ExtraValues
|
| 15 |
+
|
| 16 |
+
__all__ = (
|
| 17 |
+
'PydanticPluginProtocol',
|
| 18 |
+
'BaseValidateHandlerProtocol',
|
| 19 |
+
'ValidatePythonHandlerProtocol',
|
| 20 |
+
'ValidateJsonHandlerProtocol',
|
| 21 |
+
'ValidateStringsHandlerProtocol',
|
| 22 |
+
'NewSchemaReturns',
|
| 23 |
+
'SchemaTypePath',
|
| 24 |
+
'SchemaKind',
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]'
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SchemaTypePath(NamedTuple):
|
| 31 |
+
"""Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
|
| 32 |
+
|
| 33 |
+
module: str
|
| 34 |
+
name: str
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call']
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class PydanticPluginProtocol(Protocol):
|
| 41 |
+
"""Protocol defining the interface for Pydantic plugins."""
|
| 42 |
+
|
| 43 |
+
def new_schema_validator(
|
| 44 |
+
self,
|
| 45 |
+
schema: CoreSchema,
|
| 46 |
+
schema_type: Any,
|
| 47 |
+
schema_type_path: SchemaTypePath,
|
| 48 |
+
schema_kind: SchemaKind,
|
| 49 |
+
config: CoreConfig | None,
|
| 50 |
+
plugin_settings: dict[str, object],
|
| 51 |
+
) -> tuple[
|
| 52 |
+
ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None
|
| 53 |
+
]:
|
| 54 |
+
"""This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator]
|
| 55 |
+
is created.
|
| 56 |
+
|
| 57 |
+
It should return an event handler for each of the three validation methods, or `None` if the plugin does not
|
| 58 |
+
implement that method.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
schema: The schema to validate against.
|
| 62 |
+
schema_type: The original type which the schema was created from, e.g. the model class.
|
| 63 |
+
schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called.
|
| 64 |
+
schema_kind: The kind of schema to validate against.
|
| 65 |
+
config: The config to use for validation.
|
| 66 |
+
plugin_settings: Any plugin settings.
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
A tuple of optional event handlers for each of the three validation methods -
|
| 70 |
+
`validate_python`, `validate_json`, `validate_strings`.
|
| 71 |
+
"""
|
| 72 |
+
raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.')
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class BaseValidateHandlerProtocol(Protocol):
|
| 76 |
+
"""Base class for plugin callbacks protocols.
|
| 77 |
+
|
| 78 |
+
You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
|
| 79 |
+
typed `on_error` method.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
on_enter: Callable[..., None]
|
| 83 |
+
"""`on_enter` is changed to be more specific on all subclasses"""
|
| 84 |
+
|
| 85 |
+
def on_success(self, result: Any) -> None:
|
| 86 |
+
"""Callback to be notified of successful validation.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
result: The result of the validation.
|
| 90 |
+
"""
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
def on_error(self, error: ValidationError) -> None:
|
| 94 |
+
"""Callback to be notified of validation errors.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
error: The validation error.
|
| 98 |
+
"""
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
def on_exception(self, exception: Exception) -> None:
|
| 102 |
+
"""Callback to be notified of validation exceptions.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
exception: The exception raised during validation.
|
| 106 |
+
"""
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
| 111 |
+
"""Event handler for `SchemaValidator.validate_python`."""
|
| 112 |
+
|
| 113 |
+
def on_enter(
|
| 114 |
+
self,
|
| 115 |
+
input: Any,
|
| 116 |
+
*,
|
| 117 |
+
strict: bool | None = None,
|
| 118 |
+
extra: ExtraValues | None = None,
|
| 119 |
+
from_attributes: bool | None = None,
|
| 120 |
+
context: Any | None = None,
|
| 121 |
+
self_instance: Any | None = None,
|
| 122 |
+
by_alias: bool | None = None,
|
| 123 |
+
by_name: bool | None = None,
|
| 124 |
+
) -> None:
|
| 125 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
input: The input to be validated.
|
| 129 |
+
strict: Whether to validate the object in strict mode.
|
| 130 |
+
extra: Whether to ignore, allow, or forbid extra data during model validation.
|
| 131 |
+
from_attributes: Whether to validate objects as inputs by extracting attributes.
|
| 132 |
+
context: The context to use for validation, this is passed to functional validators.
|
| 133 |
+
self_instance: An instance of a model to set attributes on from validation, this is used when running
|
| 134 |
+
validation from the `__init__` method of a model.
|
| 135 |
+
by_alias: Whether to use the field's alias to match the input data to an attribute.
|
| 136 |
+
by_name: Whether to use the field's name to match the input data to an attribute.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
| 141 |
+
"""Event handler for `SchemaValidator.validate_json`."""
|
| 142 |
+
|
| 143 |
+
def on_enter(
|
| 144 |
+
self,
|
| 145 |
+
input: str | bytes | bytearray,
|
| 146 |
+
*,
|
| 147 |
+
strict: bool | None = None,
|
| 148 |
+
extra: ExtraValues | None = None,
|
| 149 |
+
context: Any | None = None,
|
| 150 |
+
self_instance: Any | None = None,
|
| 151 |
+
by_alias: bool | None = None,
|
| 152 |
+
by_name: bool | None = None,
|
| 153 |
+
) -> None:
|
| 154 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
input: The JSON data to be validated.
|
| 158 |
+
strict: Whether to validate the object in strict mode.
|
| 159 |
+
extra: Whether to ignore, allow, or forbid extra data during model validation.
|
| 160 |
+
context: The context to use for validation, this is passed to functional validators.
|
| 161 |
+
self_instance: An instance of a model to set attributes on from validation, this is used when running
|
| 162 |
+
validation from the `__init__` method of a model.
|
| 163 |
+
by_alias: Whether to use the field's alias to match the input data to an attribute.
|
| 164 |
+
by_name: Whether to use the field's name to match the input data to an attribute.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
StringInput: TypeAlias = 'dict[str, StringInput]'
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
|
| 172 |
+
"""Event handler for `SchemaValidator.validate_strings`."""
|
| 173 |
+
|
| 174 |
+
def on_enter(
|
| 175 |
+
self,
|
| 176 |
+
input: StringInput,
|
| 177 |
+
*,
|
| 178 |
+
strict: bool | None = None,
|
| 179 |
+
extra: ExtraValues | None = None,
|
| 180 |
+
context: Any | None = None,
|
| 181 |
+
by_alias: bool | None = None,
|
| 182 |
+
by_name: bool | None = None,
|
| 183 |
+
) -> None:
|
| 184 |
+
"""Callback to be notified of validation start, and create an instance of the event handler.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
input: The string data to be validated.
|
| 188 |
+
strict: Whether to validate the object in strict mode.
|
| 189 |
+
extra: Whether to ignore, allow, or forbid extra data during model validation.
|
| 190 |
+
context: The context to use for validation, this is passed to functional validators.
|
| 191 |
+
by_alias: Whether to use the field's alias to match the input data to an attribute.
|
| 192 |
+
by_name: Whether to use the field's name to match the input data to an attribute.
|
| 193 |
+
"""
|
miniconda3/pkgs/pydantic-2.12.4-py313h06a4308_0/lib/python3.13/site-packages/pydantic/plugin/_loader.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.metadata as importlib_metadata
|
| 4 |
+
import os
|
| 5 |
+
import warnings
|
| 6 |
+
from collections.abc import Iterable
|
| 7 |
+
from typing import TYPE_CHECKING, Final
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from . import PydanticPluginProtocol
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pydantic'
|
| 14 |
+
|
| 15 |
+
# cache of plugins
|
| 16 |
+
_plugins: dict[str, PydanticPluginProtocol] | None = None
|
| 17 |
+
# return no plugins while loading plugins to avoid recursion and errors while import plugins
|
| 18 |
+
# this means that if plugins use pydantic
|
| 19 |
+
_loading_plugins: bool = False
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_plugins() -> Iterable[PydanticPluginProtocol]:
|
| 23 |
+
"""Load plugins for Pydantic.
|
| 24 |
+
|
| 25 |
+
Inspired by: https://github.com/pytest-dev/pluggy/blob/1.3.0/src/pluggy/_manager.py#L376-L402
|
| 26 |
+
"""
|
| 27 |
+
disabled_plugins = os.getenv('PYDANTIC_DISABLE_PLUGINS')
|
| 28 |
+
global _plugins, _loading_plugins
|
| 29 |
+
if _loading_plugins:
|
| 30 |
+
# this happens when plugins themselves use pydantic, we return no plugins
|
| 31 |
+
return ()
|
| 32 |
+
elif disabled_plugins in ('__all__', '1', 'true'):
|
| 33 |
+
return ()
|
| 34 |
+
elif _plugins is None:
|
| 35 |
+
_plugins = {}
|
| 36 |
+
# set _loading_plugins so any plugins that use pydantic don't themselves use plugins
|
| 37 |
+
_loading_plugins = True
|
| 38 |
+
try:
|
| 39 |
+
for dist in importlib_metadata.distributions():
|
| 40 |
+
for entry_point in dist.entry_points:
|
| 41 |
+
if entry_point.group != PYDANTIC_ENTRY_POINT_GROUP:
|
| 42 |
+
continue
|
| 43 |
+
if entry_point.value in _plugins:
|
| 44 |
+
continue
|
| 45 |
+
if disabled_plugins is not None and entry_point.name in disabled_plugins.split(','):
|
| 46 |
+
continue
|
| 47 |
+
try:
|
| 48 |
+
_plugins[entry_point.value] = entry_point.load()
|
| 49 |
+
except (ImportError, AttributeError) as e:
|
| 50 |
+
warnings.warn(
|
| 51 |
+
f'{e.__class__.__name__} while loading the `{entry_point.name}` Pydantic plugin, '
|
| 52 |
+
f'this plugin will not be installed.\n\n{e!r}',
|
| 53 |
+
stacklevel=2,
|
| 54 |
+
)
|
| 55 |
+
finally:
|
| 56 |
+
_loading_plugins = False
|
| 57 |
+
|
| 58 |
+
return _plugins.values()
|