dash-pydantic-utils 0.14.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dash_pydantic_utils-0.14.1/.gitignore +168 -0
- dash_pydantic_utils-0.14.1/LICENSE +19 -0
- dash_pydantic_utils-0.14.1/PKG-INFO +35 -0
- dash_pydantic_utils-0.14.1/README.md +0 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/__init__.py +42 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/common.py +66 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/path.py +289 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/quantity/__init__.py +12 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/quantity/pandas.py +272 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/quantity/quantity.py +462 -0
- dash_pydantic_utils-0.14.1/dash_pydantic_utils/types.py +91 -0
- dash_pydantic_utils-0.14.1/pyproject.toml +47 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Terraform - .terraform* matches the local .lock.hcl files and modules that we do not want to export to git
|
|
10
|
+
.terraform*
|
|
11
|
+
|
|
12
|
+
# Distribution / packaging
|
|
13
|
+
.Python
|
|
14
|
+
build/
|
|
15
|
+
develop-eggs/
|
|
16
|
+
dist/
|
|
17
|
+
downloads/
|
|
18
|
+
eggs/
|
|
19
|
+
.eggs/
|
|
20
|
+
lib/
|
|
21
|
+
lib64/
|
|
22
|
+
parts/
|
|
23
|
+
sdist/
|
|
24
|
+
var/
|
|
25
|
+
wheels/
|
|
26
|
+
share/python-wheels/
|
|
27
|
+
*.egg-info/
|
|
28
|
+
.installed.cfg
|
|
29
|
+
*.egg
|
|
30
|
+
MANIFEST
|
|
31
|
+
|
|
32
|
+
# PyInstaller
|
|
33
|
+
# Usually these files are written by a python script from a template
|
|
34
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
35
|
+
*.manifest
|
|
36
|
+
*.spec
|
|
37
|
+
|
|
38
|
+
# Installer logs
|
|
39
|
+
pip-log.txt
|
|
40
|
+
pip-delete-this-directory.txt
|
|
41
|
+
|
|
42
|
+
# Unit test / coverage reports
|
|
43
|
+
htmlcov/
|
|
44
|
+
.tox/
|
|
45
|
+
.nox/
|
|
46
|
+
.coverage
|
|
47
|
+
.coverage.*
|
|
48
|
+
.cache
|
|
49
|
+
nosetests.xml
|
|
50
|
+
coverage.xml
|
|
51
|
+
*.cover
|
|
52
|
+
*.py,cover
|
|
53
|
+
.hypothesis/
|
|
54
|
+
.pytest_cache/
|
|
55
|
+
cover/
|
|
56
|
+
|
|
57
|
+
# Translations
|
|
58
|
+
*.mo
|
|
59
|
+
|
|
60
|
+
# Django stuff:
|
|
61
|
+
*.log
|
|
62
|
+
local_settings.py
|
|
63
|
+
db.sqlite3
|
|
64
|
+
db.sqlite3-journal
|
|
65
|
+
|
|
66
|
+
# Flask stuff:
|
|
67
|
+
instance/
|
|
68
|
+
.webassets-cache
|
|
69
|
+
|
|
70
|
+
# Scrapy stuff:
|
|
71
|
+
.scrapy
|
|
72
|
+
|
|
73
|
+
# Sphinx documentation
|
|
74
|
+
docs/_build/
|
|
75
|
+
|
|
76
|
+
# PyBuilder
|
|
77
|
+
.pybuilder/
|
|
78
|
+
target/
|
|
79
|
+
|
|
80
|
+
# Jupyter Notebook
|
|
81
|
+
*.ipynb
|
|
82
|
+
.ipynb_checkpoints
|
|
83
|
+
|
|
84
|
+
# IPython
|
|
85
|
+
profile_default/
|
|
86
|
+
ipython_config.py
|
|
87
|
+
|
|
88
|
+
# pyenv
|
|
89
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
90
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
91
|
+
# .python-version
|
|
92
|
+
|
|
93
|
+
# pipenv
|
|
94
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
95
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
96
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
97
|
+
# install all needed dependencies.
|
|
98
|
+
#Pipfile.lock
|
|
99
|
+
|
|
100
|
+
# poetry
|
|
101
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
102
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
103
|
+
# commonly ignored for libraries.
|
|
104
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
105
|
+
#poetry.lock
|
|
106
|
+
|
|
107
|
+
# pdm
|
|
108
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
109
|
+
#pdm.lock
|
|
110
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
111
|
+
# in version control.
|
|
112
|
+
# https://pdm.fming.dev/#use-with-ide
|
|
113
|
+
.pdm.toml
|
|
114
|
+
|
|
115
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
116
|
+
__pypackages__/
|
|
117
|
+
|
|
118
|
+
# Celery stuff
|
|
119
|
+
celerybeat-schedule
|
|
120
|
+
celerybeat.pid
|
|
121
|
+
|
|
122
|
+
# SageMath parsed files
|
|
123
|
+
*.sage.py
|
|
124
|
+
|
|
125
|
+
# Environments
|
|
126
|
+
.env
|
|
127
|
+
.venv
|
|
128
|
+
env/
|
|
129
|
+
venv/
|
|
130
|
+
ENV/
|
|
131
|
+
env.bak/
|
|
132
|
+
venv.bak/
|
|
133
|
+
|
|
134
|
+
# Spyder project settings
|
|
135
|
+
.spyderproject
|
|
136
|
+
.spyproject
|
|
137
|
+
|
|
138
|
+
# Rope project settings
|
|
139
|
+
.ropeproject
|
|
140
|
+
|
|
141
|
+
# mkdocs documentation
|
|
142
|
+
/site
|
|
143
|
+
|
|
144
|
+
# mypy
|
|
145
|
+
.mypy_cache/
|
|
146
|
+
.dmypy.json
|
|
147
|
+
dmypy.json
|
|
148
|
+
|
|
149
|
+
# Pyre type checker
|
|
150
|
+
.pyre/
|
|
151
|
+
|
|
152
|
+
# pytype static type analyzer
|
|
153
|
+
.pytype/
|
|
154
|
+
|
|
155
|
+
# Cython debug symbols
|
|
156
|
+
cython_debug/
|
|
157
|
+
|
|
158
|
+
# PyCharm
|
|
159
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
160
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
161
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
162
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
163
|
+
#.idea/
|
|
164
|
+
|
|
165
|
+
.vscode/settings.json
|
|
166
|
+
|
|
167
|
+
.bbai/*
|
|
168
|
+
.pixi/*
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
19
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dash-pydantic-utils
|
|
3
|
+
Version: 0.14.1
|
|
4
|
+
Summary: Utils for dash-pydantic-form, allows to use the utils in other places without requiring Dash.
|
|
5
|
+
Project-URL: Source, https://github.com/RenaudLN/dash-pydantic-form
|
|
6
|
+
Author-email: Renaud Lainé <renaudlaine31@gmail.com>
|
|
7
|
+
License: The MIT License (MIT)
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in
|
|
17
|
+
all copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
25
|
+
THE SOFTWARE.
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Python: <3.13,>=3.10
|
|
28
|
+
Requires-Dist: pydantic==2.*
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: dash[testing]; extra == 'dev'
|
|
31
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
33
|
+
Provides-Extra: pandas
|
|
34
|
+
Requires-Dist: numpy; extra == 'pandas'
|
|
35
|
+
Requires-Dist: pandas; extra == 'pandas'
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from .common import (
|
|
2
|
+
deep_diff,
|
|
3
|
+
deep_merge,
|
|
4
|
+
get_all_subclasses,
|
|
5
|
+
get_model_cls,
|
|
6
|
+
get_non_null_annotation,
|
|
7
|
+
is_subclass,
|
|
8
|
+
)
|
|
9
|
+
from .path import (
|
|
10
|
+
SEP,
|
|
11
|
+
from_form_data,
|
|
12
|
+
get_fullpath,
|
|
13
|
+
get_model_value,
|
|
14
|
+
get_subitem,
|
|
15
|
+
get_subitem_cls,
|
|
16
|
+
handle_discriminated,
|
|
17
|
+
model_construct_recursive,
|
|
18
|
+
set_at_path,
|
|
19
|
+
)
|
|
20
|
+
from .quantity import Quantity, QuantityDtype
|
|
21
|
+
from .types import Type
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"deep_diff",
|
|
25
|
+
"deep_merge",
|
|
26
|
+
"from_form_data",
|
|
27
|
+
"get_all_subclasses",
|
|
28
|
+
"get_fullpath",
|
|
29
|
+
"get_model_cls",
|
|
30
|
+
"get_model_value",
|
|
31
|
+
"get_non_null_annotation",
|
|
32
|
+
"get_subitem",
|
|
33
|
+
"get_subitem_cls",
|
|
34
|
+
"handle_discriminated",
|
|
35
|
+
"is_subclass",
|
|
36
|
+
"model_construct_recursive",
|
|
37
|
+
"Quantity",
|
|
38
|
+
"QuantityDtype",
|
|
39
|
+
"SEP",
|
|
40
|
+
"set_at_path",
|
|
41
|
+
"Type",
|
|
42
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from copy import deepcopy
|
|
2
|
+
from types import UnionType
|
|
3
|
+
from typing import Any, Union, get_args, get_origin
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def deep_merge(dict1: dict, dict2: dict) -> dict:
|
|
9
|
+
"""Deep merge two dictionaries, the second input is given priority."""
|
|
10
|
+
dict_final = deepcopy(dict1)
|
|
11
|
+
for key, val in dict2.items():
|
|
12
|
+
if isinstance(val, dict):
|
|
13
|
+
dict_final[key] = deep_merge(dict_final.get(key, {}), val)
|
|
14
|
+
else:
|
|
15
|
+
dict_final[key] = val
|
|
16
|
+
return dict_final
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def deep_diff(dict1: dict, dict2: dict) -> dict[str, dict | tuple[Any, Any]]:
|
|
20
|
+
"""Compute the deep difference between two dictionaries."""
|
|
21
|
+
diff = {}
|
|
22
|
+
for key in dict1.keys() | dict2.keys():
|
|
23
|
+
if isinstance(dict1.get(key), dict) and isinstance(dict2.get(key), dict):
|
|
24
|
+
sub_diff = deep_diff(dict1[key], dict2[key])
|
|
25
|
+
if sub_diff:
|
|
26
|
+
diff[key] = sub_diff
|
|
27
|
+
elif dict1.get(key) != dict2.get(key):
|
|
28
|
+
diff[key] = (dict1.get(key), dict2.get(key))
|
|
29
|
+
return diff
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_non_null_annotation(annotation: type[Any]) -> type[Any]:
|
|
33
|
+
"""Get a non-null annotation.
|
|
34
|
+
|
|
35
|
+
e.g., get_non_null_annotation(Optional[str]) = str
|
|
36
|
+
"""
|
|
37
|
+
if get_origin(annotation) in [Union, UnionType]:
|
|
38
|
+
args = tuple(x for x in get_args(annotation) if x is not type(None))
|
|
39
|
+
if len(args) == 1:
|
|
40
|
+
return args[0]
|
|
41
|
+
return Union[args] # noqa: UP007
|
|
42
|
+
return annotation
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_all_subclasses(cls: type):
|
|
46
|
+
"""Get all subclasses of a class."""
|
|
47
|
+
all_subclasses = []
|
|
48
|
+
|
|
49
|
+
for subclass in cls.__subclasses__():
|
|
50
|
+
all_subclasses.append(subclass)
|
|
51
|
+
all_subclasses.extend(get_all_subclasses(subclass))
|
|
52
|
+
|
|
53
|
+
return all_subclasses
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_model_cls(str_repr: str) -> type[BaseModel]:
|
|
57
|
+
"""Get the model class from a string representation."""
|
|
58
|
+
return next(cls for cls in get_all_subclasses(BaseModel) if str(cls) == str_repr)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_subclass(cls: type, base_cls: type) -> bool:
|
|
62
|
+
"""Check if a class is a subclass of another class, handling issubclass errors."""
|
|
63
|
+
try:
|
|
64
|
+
return issubclass(cls, base_cls)
|
|
65
|
+
except TypeError:
|
|
66
|
+
return False
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from typing import Annotated, Any, Literal, get_args, get_origin
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ValidationError, create_model
|
|
7
|
+
from pydantic.fields import FieldInfo
|
|
8
|
+
from pydantic_core import PydanticUndefined
|
|
9
|
+
|
|
10
|
+
from dash_pydantic_utils.common import get_non_null_annotation, is_subclass
|
|
11
|
+
from dash_pydantic_utils.types import Type
|
|
12
|
+
|
|
13
|
+
SEP = ":"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_model_value(item: BaseModel, field: str, parent: str, allow_default: bool = True): # noqa: PLR0911
|
|
17
|
+
"""Get the value of a model (parent, field) pair.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
item: BaseModel
|
|
22
|
+
The object to get the value from
|
|
23
|
+
field: str
|
|
24
|
+
The field name
|
|
25
|
+
parent: str
|
|
26
|
+
The parent of the field (for nested fields), in dot notation
|
|
27
|
+
allow_default: bool
|
|
28
|
+
Allow to return the default value, when the object has been created with model_construct.
|
|
29
|
+
"""
|
|
30
|
+
try:
|
|
31
|
+
subitem = get_subitem(item, parent)
|
|
32
|
+
if isinstance(subitem, BaseModel):
|
|
33
|
+
return subitem[field]
|
|
34
|
+
if isinstance(subitem, dict) and isinstance(field, int):
|
|
35
|
+
return list(subitem.values())[field]
|
|
36
|
+
if isinstance(subitem, list) and isinstance(field, int):
|
|
37
|
+
return subitem[field]
|
|
38
|
+
return subitem[field]
|
|
39
|
+
except:
|
|
40
|
+
if allow_default:
|
|
41
|
+
subitem_cls = get_subitem_cls(item.__class__, parent, item=item)
|
|
42
|
+
if not is_subclass(subitem_cls, BaseModel):
|
|
43
|
+
return None
|
|
44
|
+
field_info = subitem_cls.model_fields[field]
|
|
45
|
+
if field_info.default is not PydanticUndefined:
|
|
46
|
+
return field_info.default
|
|
47
|
+
if field_info.default_factory:
|
|
48
|
+
return field_info.default_factory()
|
|
49
|
+
return None
|
|
50
|
+
raise
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_subitem(item: BaseModel | list | dict, parent: str) -> BaseModel:
|
|
54
|
+
"""Get the subitem of a model at a given parent.
|
|
55
|
+
|
|
56
|
+
e.g., get_subitem(person, "au_metadata") = AUMetadata(param1=True, param2=False)
|
|
57
|
+
"""
|
|
58
|
+
if parent == "":
|
|
59
|
+
return item
|
|
60
|
+
|
|
61
|
+
path = parent.split(SEP)
|
|
62
|
+
|
|
63
|
+
first_part = path[0]
|
|
64
|
+
if isinstance(first_part, str) and first_part.isdigit():
|
|
65
|
+
first_part = int(first_part)
|
|
66
|
+
|
|
67
|
+
if isinstance(item, BaseModel):
|
|
68
|
+
next_item = getattr(item, first_part)
|
|
69
|
+
elif isinstance(item, dict) and isinstance(first_part, int):
|
|
70
|
+
next_item = list(item.values())[first_part]
|
|
71
|
+
elif isinstance(item, list) and isinstance(first_part, int):
|
|
72
|
+
next_item = item[first_part]
|
|
73
|
+
elif is_idx_template(first_part):
|
|
74
|
+
next_item = None
|
|
75
|
+
else:
|
|
76
|
+
next_item = item.get(first_part)
|
|
77
|
+
|
|
78
|
+
if len(path) == 1 or next_item is None:
|
|
79
|
+
return next_item
|
|
80
|
+
|
|
81
|
+
return get_subitem(next_item, SEP.join(path[1:]))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_idx_template(val: str):
|
|
85
|
+
"""Check if a string is an index template."""
|
|
86
|
+
return bool(re.findall(r"^\{\{[\w|\{\}]+\}\}$", val))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_subitem_cls(model: type[BaseModel], parent: str, item: BaseModel | None = None) -> type[BaseModel]:
|
|
90
|
+
"""Get the subitem class of a model at a given parent.
|
|
91
|
+
|
|
92
|
+
e.g., get_subitem_cls(Person, "au_metadata") = AUMetadata
|
|
93
|
+
"""
|
|
94
|
+
if parent == "":
|
|
95
|
+
return model
|
|
96
|
+
|
|
97
|
+
path = parent.split(SEP)
|
|
98
|
+
|
|
99
|
+
first_part = path[0]
|
|
100
|
+
second_part = None
|
|
101
|
+
|
|
102
|
+
if len(path) == 1:
|
|
103
|
+
ann = get_non_null_annotation(model.model_fields[first_part].annotation)
|
|
104
|
+
return ann
|
|
105
|
+
|
|
106
|
+
second_part = path[1]
|
|
107
|
+
if isinstance(second_part, str) and second_part.isdigit():
|
|
108
|
+
second_part = int(second_part)
|
|
109
|
+
|
|
110
|
+
field_info = model.model_fields[first_part] if is_subclass(model, BaseModel) else (item.model_fields[first_part])
|
|
111
|
+
first_annotation = get_non_null_annotation(field_info.annotation)
|
|
112
|
+
try:
|
|
113
|
+
subitem = get_subitem(item, first_part) if item is not None else None
|
|
114
|
+
except: # noqa: E722
|
|
115
|
+
subitem = None
|
|
116
|
+
if Type.classify(first_annotation, field_info.discriminator) == Type.DISCRIMINATED_MODEL:
|
|
117
|
+
if not item:
|
|
118
|
+
raise TypeError("Discriminated models with nesting need passing item data to be displayed")
|
|
119
|
+
discriminator_value = None if subitem is None else getattr(subitem, field_info.discriminator, None)
|
|
120
|
+
subitem_cls, _ = handle_discriminated(
|
|
121
|
+
item.__class__, parent, first_annotation, field_info.discriminator, discriminator_value
|
|
122
|
+
)
|
|
123
|
+
return get_subitem_cls(subitem_cls, SEP.join(path[1:]), item=subitem)
|
|
124
|
+
if (
|
|
125
|
+
get_origin(first_annotation) is list
|
|
126
|
+
and (isinstance(second_part, int) or is_idx_template(second_part))
|
|
127
|
+
and get_args(first_annotation)
|
|
128
|
+
):
|
|
129
|
+
try:
|
|
130
|
+
subitem = subitem[second_part] if subitem is not None else None
|
|
131
|
+
except: # noqa: E722
|
|
132
|
+
subitem = None
|
|
133
|
+
return get_subitem_cls(
|
|
134
|
+
get_non_null_annotation(get_args(first_annotation)[0]),
|
|
135
|
+
SEP.join(path[2:]),
|
|
136
|
+
item=subitem,
|
|
137
|
+
)
|
|
138
|
+
if get_origin(first_annotation) is dict and (isinstance(second_part, int | str)) and get_args(first_annotation):
|
|
139
|
+
return get_subitem_cls(
|
|
140
|
+
get_non_null_annotation(get_args(first_annotation)[1]),
|
|
141
|
+
SEP.join(path[2:]),
|
|
142
|
+
item=subitem,
|
|
143
|
+
)
|
|
144
|
+
return get_subitem_cls(first_annotation, SEP.join(path[1:]), item=subitem)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def handle_discriminated(model: type[BaseModel], parent: str, annotation: type, disc_field: str, disc_val: Any):
|
|
148
|
+
"""Handle a discriminated model."""
|
|
149
|
+
all_vals = set()
|
|
150
|
+
out = None
|
|
151
|
+
if get_origin(annotation) is Annotated:
|
|
152
|
+
if disc_field is None:
|
|
153
|
+
disc_field = next(
|
|
154
|
+
(f.discriminator for f in get_args(annotation)[1:] if isinstance(f, FieldInfo)),
|
|
155
|
+
None,
|
|
156
|
+
)
|
|
157
|
+
annotation = get_args(annotation)[0]
|
|
158
|
+
for possible in get_args(annotation):
|
|
159
|
+
if not get_origin(possible.model_fields[disc_field].annotation) == Literal:
|
|
160
|
+
raise ValueError("Discriminator must be a Literal")
|
|
161
|
+
|
|
162
|
+
vals = get_args(possible.model_fields[disc_field].annotation)
|
|
163
|
+
all_vals = all_vals.union(vals)
|
|
164
|
+
if disc_val is not None and disc_val in vals:
|
|
165
|
+
out = possible
|
|
166
|
+
|
|
167
|
+
all_vals = tuple(all_vals)
|
|
168
|
+
|
|
169
|
+
if disc_val is None:
|
|
170
|
+
return create_model(
|
|
171
|
+
f"{model.__name__}{parent.replace(SEP, ' ').title().replace(' ', '')}Discriminator",
|
|
172
|
+
**{disc_field: (Literal[tuple(all_vals)], ...)},
|
|
173
|
+
), all_vals
|
|
174
|
+
|
|
175
|
+
if out is None:
|
|
176
|
+
raise ValueError(f"Invalid discriminator value: {disc_val}")
|
|
177
|
+
|
|
178
|
+
return out, all_vals
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def get_fullpath(*parts, sep: str = SEP):
|
|
182
|
+
"""Creates the full path of a field from its name and parent."""
|
|
183
|
+
return sep.join([str(p) for p in parts]).strip(sep)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def model_construct_recursive(data: dict, data_model: type[BaseModel]):
|
|
187
|
+
"""Construct a model recursively."""
|
|
188
|
+
updated = deepcopy(data)
|
|
189
|
+
for key, val in data.items():
|
|
190
|
+
if key not in data_model.model_fields:
|
|
191
|
+
continue
|
|
192
|
+
if val is None:
|
|
193
|
+
updated[key] = None
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
field_info = data_model.model_fields[key]
|
|
197
|
+
ann = get_non_null_annotation(field_info.annotation)
|
|
198
|
+
type_ = Type.classify(ann, field_info.discriminator)
|
|
199
|
+
if type_ == Type.MODEL:
|
|
200
|
+
updated[key] = model_construct_recursive(val, ann)
|
|
201
|
+
elif type_ == Type.DISCRIMINATED_MODEL:
|
|
202
|
+
updated[key] = _construct_handle_discriminated(val, field_info.discriminator, ann)
|
|
203
|
+
elif type_ == Type.MODEL_LIST and isinstance(val, list):
|
|
204
|
+
updated[key] = [model_construct_recursive(vv, get_args(ann)[0]) for vv in val]
|
|
205
|
+
elif type_ == Type.DISCRIMINATED_MODEL_LIST and isinstance(val, list):
|
|
206
|
+
new_val = []
|
|
207
|
+
sub_ann = get_args(ann)[0]
|
|
208
|
+
# Note: since we have a DISCRIMINATED_MODEL_LIST, sub_ann will be an Annotated union with discriminator
|
|
209
|
+
sub_ann2 = get_args(sub_ann)[0]
|
|
210
|
+
discriminator = next((f.discriminator for f in get_args(sub_ann)[1:] if isinstance(f, FieldInfo)), None)
|
|
211
|
+
for vv in val:
|
|
212
|
+
new_val.append(_construct_handle_discriminated(vv, discriminator, sub_ann2))
|
|
213
|
+
updated[key] = new_val
|
|
214
|
+
elif type_ == Type.DISCRIMINATED_MODEL_DICT and isinstance(val, dict):
|
|
215
|
+
new_val = {}
|
|
216
|
+
sub_ann = get_args(ann)[1]
|
|
217
|
+
# Note: since we have a DISCRIMINATED_MODEL_LIST, sub_ann will be an Annotated union with discriminator
|
|
218
|
+
sub_ann2 = get_args(sub_ann)[0]
|
|
219
|
+
discriminator = next((f.discriminator for f in get_args(sub_ann)[1:] if isinstance(f, FieldInfo)), None)
|
|
220
|
+
for kk, vv in val.items():
|
|
221
|
+
new_val[kk] = _construct_handle_discriminated(vv, discriminator, sub_ann2)
|
|
222
|
+
updated[key] = new_val
|
|
223
|
+
|
|
224
|
+
return data_model.model_construct(**updated)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _construct_handle_discriminated(val: dict, discriminator: str | None, ann: type):
|
|
228
|
+
if discriminator is None or discriminator not in val:
|
|
229
|
+
return val
|
|
230
|
+
|
|
231
|
+
disc_val = val[discriminator]
|
|
232
|
+
out = None
|
|
233
|
+
for possible in get_args(ann):
|
|
234
|
+
if not get_origin(possible.model_fields[discriminator].annotation) == Literal:
|
|
235
|
+
raise ValueError("Discriminator must be a Literal")
|
|
236
|
+
|
|
237
|
+
if disc_val in get_args(possible.model_fields[discriminator].annotation):
|
|
238
|
+
out = possible
|
|
239
|
+
break
|
|
240
|
+
|
|
241
|
+
if out is not None:
|
|
242
|
+
return model_construct_recursive(val, out)
|
|
243
|
+
return val
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def from_form_data(data: dict, data_model: type[BaseModel]):
|
|
247
|
+
"""Construct a model from form data, allowing to use default values when validation of a field fails."""
|
|
248
|
+
try:
|
|
249
|
+
return data_model.model_validate(data)
|
|
250
|
+
except ValidationError as exc:
|
|
251
|
+
data_with_defaults = deepcopy(data)
|
|
252
|
+
defaulted_fields = []
|
|
253
|
+
for error in exc.errors():
|
|
254
|
+
path_parts = [str(x) for x in error["loc"]]
|
|
255
|
+
for i in range(len(path_parts), 0, -1):
|
|
256
|
+
parts_extract = path_parts[:i]
|
|
257
|
+
path = SEP.join(parts_extract)
|
|
258
|
+
try:
|
|
259
|
+
failing_model = get_subitem_cls(data_model, SEP.join(parts_extract[:-1]))
|
|
260
|
+
except AttributeError:
|
|
261
|
+
continue
|
|
262
|
+
if not is_subclass(failing_model, BaseModel):
|
|
263
|
+
continue
|
|
264
|
+
field = failing_model.model_fields[parts_extract[-1]]
|
|
265
|
+
if field.default != PydanticUndefined:
|
|
266
|
+
set_at_path(data_with_defaults, path, field.default)
|
|
267
|
+
defaulted_fields.append(path)
|
|
268
|
+
break
|
|
269
|
+
if field.default_factory is not None:
|
|
270
|
+
set_at_path(data_with_defaults, path, field.default_factory())
|
|
271
|
+
defaulted_fields.append(path)
|
|
272
|
+
break
|
|
273
|
+
|
|
274
|
+
if defaulted_fields:
|
|
275
|
+
logging.info(
|
|
276
|
+
"Could not validate the following fields: %s for %s, using default values instead.",
|
|
277
|
+
defaulted_fields,
|
|
278
|
+
data_model.__name__,
|
|
279
|
+
)
|
|
280
|
+
return data_model.model_validate(data_with_defaults)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def set_at_path(data: dict, path: str, value: Any):
|
|
284
|
+
"""Set a value at a path in a dictionary."""
|
|
285
|
+
parts = path.split(SEP)
|
|
286
|
+
pointer = data
|
|
287
|
+
for part in parts[:-1]:
|
|
288
|
+
pointer = pointer.get(part, pointer[int(part)])
|
|
289
|
+
pointer[parts[-1]] = value
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from pydantic import BaseModel
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from .pandas import Quantity, QuantityDtype
|
|
5
|
+
except ModuleNotFoundError:
|
|
6
|
+
from .quantity import Quantity
|
|
7
|
+
|
|
8
|
+
QuantityDtype = None
|
|
9
|
+
|
|
10
|
+
BaseModel.__getitem__ = lambda self, key: self.__dict__.get(key)
|
|
11
|
+
|
|
12
|
+
__all__ = ["Quantity", "QuantityDtype"]
|