dash-pydantic-utils 0.14.0__py3-none-any.whl

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.
@@ -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"]
@@ -0,0 +1,272 @@
1
+ # ruff: noqa
2
+ # TODO: ^
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import ClassVar
7
+
8
+ import numpy as np
9
+ import numpy.typing as npt
10
+ import pandas as pd
11
+ from pandas.core import ops
12
+ from pandas.core.algorithms import take
13
+ from pandas.core.arrays.numeric import NumericArray, NumericDtype
14
+ from pandas.core.dtypes.base import register_extension_dtype
15
+ from pandas.core.dtypes.common import is_bool, is_float_dtype, pandas_dtype
16
+ from pandas.core.dtypes.missing import isna, notna
17
+ from pandas.core.indexers import check_array_indexer
18
+ from pandas.util._decorators import cache_readonly
19
+
20
+ from .quantity import ISUnits
21
+ from .quantity import Quantity as Quantity_
22
+
23
+
24
+ class Quantity(Quantity_):
25
+ value: float | np.ndarray
26
+ model_config = {"arbitrary_types_allowed": True}
27
+
28
+ def __str__(self) -> str:
29
+ if isinstance(self.value, np.ndarray):
30
+ return f"{self.value}, {self.unit}"
31
+ return super().__str__()
32
+
33
+ @property
34
+ def dtype(self):
35
+ return QuantityDtype(unit=self.unit)
36
+
37
+
38
+ @register_extension_dtype
39
+ class QuantityDtype(NumericDtype):
40
+ type = np.float64
41
+ name: ClassVar[str] = "Quantity"
42
+ _metadata = ("unit",)
43
+ _default_np_dtype = np.dtype(np.float64)
44
+ _checker = is_float_dtype
45
+
46
+ @property
47
+ def name(self) -> str:
48
+ return f"Quantity[{self.unit}]"
49
+
50
+ def __init__(self, unit: str, *args, **kwargs):
51
+ super().__init__(*args, **kwargs)
52
+ self.unit = unit
53
+
54
+ def __repr__(self):
55
+ return f"QuantityDtype({self.unit})"
56
+
57
+ @classmethod
58
+ def construct_array_type(cls) -> type[QuantityArray]:
59
+ """
60
+ Return the array type associated with this dtype.
61
+
62
+ Returns
63
+ -------
64
+ type
65
+ """
66
+ return QuantityArray
67
+
68
+ @classmethod
69
+ def construct_from_string(cls, string: str):
70
+ try:
71
+ unit = re.findall(r"^Quantity\[(.*)\]$", string)[0]
72
+ return cls(unit=unit)
73
+ except Exception as exc:
74
+ raise TypeError(f"Cannot construct QuantityDtype from {string}") from exc
75
+
76
+ @classmethod
77
+ def _safe_cast(cls, values: np.ndarray, dtype: np.dtype, copy: bool) -> np.ndarray:
78
+ """
79
+ Safely cast the values to the given dtype.
80
+
81
+ "safe" in this context means the casting is lossless.
82
+ """
83
+ # This is really only here for compatibility with IntegerDtype
84
+ # Here for compat with IntegerDtype
85
+ return values.astype(dtype, copy=copy)
86
+
87
+ def __from_arrow__(self, array, **kwargs):
88
+ import pyarrow
89
+ from pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask
90
+
91
+ array_class = self.construct_array_type()
92
+
93
+ pyarrow_type = pyarrow.from_numpy_dtype(self.type)
94
+ if not array.type.equals(pyarrow_type) and not pyarrow.types.is_null(array.type):
95
+ # test_from_arrow_type_error raise for string, but allow
96
+ # through itemsize conversion GH#31896
97
+ rt_dtype = pandas_dtype(array.type.to_pandas_dtype())
98
+ if rt_dtype.kind not in "iuf":
99
+ # Could allow "c" or potentially disallow float<->int conversion,
100
+ # but at the moment we specifically test that uint<->int works
101
+ raise TypeError(f"Expected array of {self} type, got {array.type} instead")
102
+
103
+ array = array.cast(pyarrow_type)
104
+
105
+ if isinstance(array, pyarrow.ChunkedArray):
106
+ # TODO this "if" can be removed when requiring pyarrow >= 10.0, which fixed
107
+ # combine_chunks for empty arrays https://github.com/apache/arrow/pull/13757
108
+ array = pyarrow.array([], type=array.type) if array.num_chunks == 0 else array.combine_chunks()
109
+
110
+ data, mask = pyarrow_array_to_numpy_and_mask(array, dtype=self.numpy_dtype)
111
+ return array_class(self.unit, data.copy(), ~mask, copy=False)
112
+
113
+ def _get_common_dtype(self, dtypes: list):
114
+ if not all(isinstance(dtype, QuantityDtype) for dtype in dtypes):
115
+ raise ValueError("No common dtype between Quantity and non-Quantity types")
116
+ raise ValueError("No common dtype between Quantity with different units")
117
+
118
+ def __eq__(self, other):
119
+ return isinstance(other, QuantityDtype) and self.unit == other.unit
120
+
121
+ def __hash__(self):
122
+ return hash(str(self))
123
+
124
+
125
+ class QuantityArray(NumericArray):
126
+ _dtype_cls = QuantityDtype
127
+ _internal_fill_value = np.nan
128
+
129
+ @cache_readonly
130
+ def dtype(self) -> NumericDtype:
131
+ return QuantityDtype(unit=self.unit)
132
+
133
+ def __init__(self, unit: str, values: np.ndarray, mask: npt.NDArray[np.bool_], copy: bool = False):
134
+ self.unit = unit
135
+ super().__init__(values, mask, copy=copy)
136
+
137
+ @classmethod
138
+ def _from_sequence(cls, scalars, *, dtype=None, copy: bool = False):
139
+ values, mask = cls._coerce_to_array(scalars, dtype=dtype, copy=copy)
140
+ return cls(unit=dtype.unit, values=values, mask=mask)
141
+
142
+ def _arith_method(self, other, op):
143
+ pd_op = ops.get_array_op(op)
144
+ self_q = Quantity(value=self._data, unit=self.dtype.unit)
145
+ mask = self._mask
146
+ if isinstance(other, QuantityArray):
147
+ other_q = Quantity(value=other._data, unit=other.dtype.unit)
148
+ mask |= other._mask
149
+ elif isinstance(other, Quantity | float | int):
150
+ other_q = other
151
+ result = pd_op(self_q, other_q)
152
+ if not isinstance(result, Quantity):
153
+ result = Quantity(value=result, unit="")
154
+ return self._maybe_mask_result(result, mask)
155
+
156
+ def _maybe_mask_result(self, result: Quantity, mask: np.ndarray):
157
+ if not isinstance(result, Quantity):
158
+ result = Quantity(value=result, unit=self.unit)
159
+ return QuantityArray(result.unit, result.value, mask, copy=False)
160
+
161
+ def copy(self):
162
+ data = self._data.copy()
163
+ mask = self._mask.copy()
164
+ return self.__class__(unit=self.unit, values=data, mask=mask)
165
+
166
+ def to(self, other_unit: str):
167
+ new_value = Quantity(value=self._data, unit=self.unit).to(other_unit).value
168
+ return self.__class__(value=new_value, unit=other_unit)
169
+
170
+ def __repr__(self):
171
+ return repr(Quantity(value=self._data, unit=self.unit))
172
+
173
+ def __getitem__(self, item):
174
+ item = check_array_indexer(self, item)
175
+
176
+ newmask = self._mask[item]
177
+ if is_bool(newmask):
178
+ # This is a scalar indexing
179
+ if newmask:
180
+ return self.dtype.na_value
181
+ return Quantity(value=self._data[item], unit=self.unit)
182
+
183
+ return self.__class__(self.unit, self._data[item], newmask)
184
+
185
+ def take(
186
+ self,
187
+ indexer,
188
+ *,
189
+ allow_fill: bool = False,
190
+ fill_value=None,
191
+ axis=0,
192
+ ):
193
+ # we always fill with 1 internally
194
+ # to avoid upcasting
195
+ data_fill_value = self._internal_fill_value if isna(fill_value) else fill_value
196
+ result = take(
197
+ self._data,
198
+ indexer,
199
+ fill_value=data_fill_value,
200
+ allow_fill=allow_fill,
201
+ axis=axis,
202
+ )
203
+
204
+ mask = take(self._mask, indexer, fill_value=True, allow_fill=allow_fill, axis=axis)
205
+
206
+ # if we are filling
207
+ # we only fill where the indexer is null
208
+ # not existing missing values
209
+ # TODO(jreback) what if we have a non-na float as a fill value?
210
+ if allow_fill and notna(fill_value):
211
+ fill_mask = np.asarray(indexer) == -1
212
+ result[fill_mask] = fill_value
213
+ mask = mask ^ fill_mask
214
+
215
+ return self.__class__(self.unit, result, mask)
216
+
217
+ @classmethod
218
+ def _concat_same_type(
219
+ cls,
220
+ to_concat,
221
+ axis=0,
222
+ ):
223
+ unit = to_concat[0].unit
224
+ if not all(x.unit == unit for x in to_concat):
225
+ raise ValueError("Can only concatenate Quantity with the same unit")
226
+ data = np.concatenate([x._data for x in to_concat], axis=axis)
227
+ mask = np.concatenate([x._mask for x in to_concat], axis=axis)
228
+ return cls(unit, data, mask)
229
+
230
+
231
+ @pd.api.extensions.register_series_accessor("qt")
232
+ class QuantityAccessor:
233
+ def __init__(self, pandas_obj: pd.Series):
234
+ self._obj = pandas_obj
235
+
236
+ def to(self, other_unit: str):
237
+ new_value = Quantity(value=self._obj.to_numpy(), unit=self._obj.dtype.unit).to(other_unit).value
238
+ return pd.Series(new_value, index=self._obj.index, dtype=QuantityDtype(unit=other_unit))
239
+
240
+
241
+ @pd.api.extensions.register_dataframe_accessor("qt")
242
+ class QuantityAccessor:
243
+ def __init__(self, pandas_obj: pd.DataFrame):
244
+ self._obj = pandas_obj
245
+
246
+ def to(self, other_unit: str):
247
+ if not all(isinstance(dtype, QuantityDtype) for dtype in self._obj.dtypes.values):
248
+ raise ValueError("Can only convert a DataFrame of Quantity")
249
+ if len(set(self._obj.dtypes.values)) != 1:
250
+ raise ValueError("Can only convert a DataFrame of Quantity with the same unit")
251
+
252
+ unit = self._obj.dtypes.values[0].unit
253
+ new_value = Quantity(value=self._obj.to_numpy(), unit=unit).to(other_unit).value
254
+ return pd.DataFrame(
255
+ new_value, index=self._obj.index, columns=self._obj.columns, dtype=QuantityDtype(unit=other_unit)
256
+ )
257
+
258
+ def find(self, unit: str | None = None, category: str | None = None, i_s_units: ISUnits | str | None = None):
259
+ if not any([unit, category, i_s_units]):
260
+ return self._obj[[col for col, dtype in self._obj.dtypes.items() if isinstance(dtype, QuantityDtype)]]
261
+
262
+ if unit:
263
+ return self._obj[self._obj.dtypes[self._obj.dtypes == QuantityDtype(unit)].index]
264
+ if isinstance(i_s_units, str):
265
+ i_s_units = ISUnits.from_str(i_s_units)
266
+ cols = []
267
+ for col, dtype in self._obj.dtypes.items():
268
+ if isinstance(dtype, QuantityDtype):
269
+ col_i_s_units, _, col_category = Quantity.get_unit_info(dtype.unit)
270
+ if (category and col_category == category) or (i_s_units and col_i_s_units == i_s_units):
271
+ cols.append(col)
272
+ return self._obj[cols]
@@ -0,0 +1,462 @@
1
+ import re
2
+ from collections.abc import Mapping
3
+ from copy import deepcopy
4
+ from functools import lru_cache
5
+ from itertools import permutations
6
+ from typing import ClassVar, TypedDict, Union
7
+
8
+ from pydantic import BaseModel, ConfigDict, field_validator
9
+
10
+ PREFIX_MULTIPLIERS = {
11
+ "n": 1e-9,
12
+ "u": 1e-6,
13
+ "m": 1e-3,
14
+ "c": 1e-2,
15
+ "d": 1e-1,
16
+ "D": 1e1,
17
+ "h": 1e2,
18
+ "k": 1e3,
19
+ "M": 1e6,
20
+ "G": 1e9,
21
+ "T": 1e12,
22
+ }
23
+
24
+
25
+ class ISUnits(BaseModel):
26
+ """International system units + money unit."""
27
+
28
+ kg: int = 0
29
+ m: int = 0
30
+ s: int = 0
31
+ A: int = 0
32
+ K: int = 0
33
+ mol: int = 0
34
+ cd: int = 0
35
+ """Extend IS units to money quantities."""
36
+ USD: int = 0
37
+
38
+ model_config = ConfigDict(extra="forbid")
39
+
40
+ def is_empty(self) -> bool:
41
+ """Check if the model is empty."""
42
+ return all(getattr(self, field) == 0 for field in self.model_fields)
43
+
44
+ def __hash__(self):
45
+ """The hash function."""
46
+ return hash(frozenset(self.model_dump().items()))
47
+
48
+ def __mul__(self, other: "ISUnits") -> "ISUnits":
49
+ """Multiply two IS units."""
50
+ return self.__class__(**{field: getattr(self, field) + getattr(other, field) for field in self.model_fields})
51
+
52
+ def __truediv__(self, other: "ISUnits") -> "ISUnits":
53
+ """Divide two IS units."""
54
+ return self.__class__(**{field: getattr(self, field) - getattr(other, field) for field in self.model_fields})
55
+
56
+ def __pow__(self, other: int) -> "ISUnits":
57
+ """Raise to power."""
58
+ return self.__class__(**{field: getattr(self, field) * other for field in self.model_fields})
59
+
60
+ def __repr__(self) -> str:
61
+ """Representation."""
62
+ return f"ISUnits({self})"
63
+
64
+ def __str__(self) -> str:
65
+ """String representation."""
66
+ return "*".join([unit + (f"^{pow}" if pow != 1 else "") for unit, pow in self.model_dump().items() if pow])
67
+
68
+ @classmethod
69
+ def from_str(cls, unit_str: str) -> "ISUnits":
70
+ """Create from string."""
71
+ return cls(
72
+ **{
73
+ unit: int(pow) if pow else 1
74
+ for unit, pow in re.findall(r"(kg|m|s|K|A|mol|cd|USD)(?:\^(\-*\d+))*(?:\*|$)", unit_str)
75
+ }
76
+ )
77
+
78
+
79
+ class NameData(TypedDict):
80
+ """Name data."""
81
+
82
+ unit: str
83
+ category: str
84
+
85
+
86
+ class Quantity(BaseModel):
87
+ """Quantity model."""
88
+
89
+ value: float
90
+ unit: str | None
91
+
92
+ """Conversion factors from unit to IS unit."""
93
+ conversion: ClassVar[dict[ISUnits, Mapping[str, float]]] = {
94
+ # Unitless
95
+ ISUnits(): {
96
+ "": 1,
97
+ "%": 0.01,
98
+ "‰": 0.001,
99
+ },
100
+ # Money
101
+ ISUnits(USD=1): {
102
+ "USD": 1,
103
+ "EUR": 1.07,
104
+ "GBP": 1.30,
105
+ "AUD": 0.67,
106
+ "JPY": 0.0067,
107
+ "CAD": 0.73,
108
+ "CHF": 1.16,
109
+ "CNY": 0.14,
110
+ "NZD": 0.61,
111
+ "ZAR": 0.057,
112
+ "INR": 0.012,
113
+ },
114
+ # Length
115
+ ISUnits(m=1): {
116
+ "m": 1,
117
+ "mi": 1609.344,
118
+ "NM": 1852,
119
+ "ft": 0.3048,
120
+ "in": 0.0254,
121
+ },
122
+ # Mass
123
+ ISUnits(kg=1): {
124
+ "kg": 1,
125
+ "g": 0.001,
126
+ "lb": 0.453592,
127
+ "oz": 0.0283495,
128
+ },
129
+ # Time
130
+ ISUnits(s=1): {
131
+ "s": 1,
132
+ "min": 60,
133
+ "h": 3600,
134
+ "d": 86400,
135
+ },
136
+ # Force
137
+ ISUnits(kg=1, m=1, s=-2): {
138
+ "N": 1,
139
+ },
140
+ # Pressure
141
+ ISUnits(kg=1, m=-1, s=-2): {
142
+ "Pa": 1,
143
+ "atm": 101325,
144
+ "psi": 6894.76,
145
+ },
146
+ # Energy
147
+ ISUnits(kg=1, m=2, s=-2): {
148
+ "J": 1,
149
+ "Wh": 3600,
150
+ "cal": 4.184,
151
+ },
152
+ # Frequency
153
+ ISUnits(s=-1): {
154
+ "Hz": 1,
155
+ },
156
+ # Temperature
157
+ ISUnits(K=1): {
158
+ "K": 1,
159
+ "C": (1, 273.15),
160
+ "F": (5 / 9, 273.15 - 5 / 9 * 32),
161
+ },
162
+ # Power
163
+ ISUnits(kg=1, m=2, s=-3): {
164
+ "W": 1,
165
+ "hp": 745.7,
166
+ },
167
+ # Area
168
+ ISUnits(m=2): {
169
+ "m^2": 1,
170
+ "ha": 10000,
171
+ "acre": 4046.86,
172
+ "in^2": 0.00064516,
173
+ "ft^2": 0.092903,
174
+ "mi^2": 2589988.1,
175
+ },
176
+ # Volume
177
+ ISUnits(m=3): {
178
+ "m^3": 1,
179
+ "L": 0.001,
180
+ "gal": 0.00378541,
181
+ },
182
+ # Speed
183
+ ISUnits(m=1, s=-1): {
184
+ "m/s": 1,
185
+ "mph": 0.44704,
186
+ "kph": 1 / 3.6,
187
+ },
188
+ # Acceleration
189
+ ISUnits(m=1, s=-2): {
190
+ "m/s^2": 1,
191
+ },
192
+ }
193
+ names: ClassVar[dict[ISUnits, NameData]] = {
194
+ ISUnits(): {"category": "Unitless", "unit": ""},
195
+ ISUnits(USD=1): {"category": "Money", "unit": "USD"},
196
+ ISUnits(m=1): {"category": "Length", "unit": "m"},
197
+ ISUnits(kg=1): {"category": "Mass", "unit": "kg"},
198
+ ISUnits(s=1): {"category": "Time", "unit": "s"},
199
+ ISUnits(K=1): {"category": "Temperature", "unit": "K"},
200
+ ISUnits(s=-1): {"category": "Frequency", "unit": "Hz"},
201
+ ISUnits(kg=1, m=1, s=-2): {"category": "Force", "unit": "N"},
202
+ ISUnits(kg=1, m=-1, s=-2): {"category": "Pressure", "unit": "Pa"},
203
+ ISUnits(kg=1, m=2, s=-2): {"category": "Energy", "unit": "J"},
204
+ ISUnits(kg=1, m=2, s=-3): {"category": "Power", "unit": "W"},
205
+ ISUnits(m=2): {"category": "Area", "unit": "m^2"},
206
+ ISUnits(m=3): {"category": "Volume", "unit": "m^3"},
207
+ ISUnits(m=1, s=-1): {"category": "Speed", "unit": "m/s"},
208
+ ISUnits(m=1, s=-2): {"category": "Acceleration", "unit": "m/s^2"},
209
+ }
210
+
211
+ def __init__(self, value: float, unit: str):
212
+ super().__init__(value=value, unit=unit)
213
+
214
+ @property
215
+ def unit_multiplier(self) -> tuple[float, float]:
216
+ """Get multiplier."""
217
+ return self.get_unit_info(self.unit)[1]
218
+
219
+ @property
220
+ def i_s_units(self) -> ISUnits:
221
+ """Get IS units."""
222
+ return self.get_unit_info(self.unit)[0]
223
+
224
+ @property
225
+ def category(self) -> str:
226
+ """Get category."""
227
+ return self.get_unit_info(self.unit)[2]
228
+
229
+ @classmethod
230
+ @lru_cache
231
+ def get_unit_info(cls, unit: str) -> tuple[ISUnits, tuple[float, float], str]:
232
+ """Get information about a given unit."""
233
+ i_s_pattern = re.compile("^((kg|m|s|K|USD|A|mol|cd)(?:\^(\-*\d+))*(?:\*|$))+$")
234
+ # IS units repr
235
+ if re.match(i_s_pattern, unit):
236
+ i_s_units = ISUnits.from_str(unit)
237
+ return i_s_units, (1, 0), cls.names.get(i_s_units, {}).get("category", "Quantity")
238
+
239
+ all_units = sum([list(units) for units in cls.conversion.values()], [])
240
+
241
+ def trim_prefixes(unit: str) -> str:
242
+ if unit in all_units:
243
+ return unit, None
244
+ for prefix in PREFIX_MULTIPLIERS:
245
+ if unit.startswith(prefix):
246
+ base_unit = unit.removeprefix(prefix)
247
+ if base_unit in all_units:
248
+ return base_unit, prefix
249
+ raise ValueError(f"Unsupported unit: {unit}")
250
+
251
+ i_s_units = ISUnits()
252
+ factor, base = 1.0, 0.0
253
+ for i, unit_ in enumerate(unit.split("/")):
254
+ base_unit, prefix = trim_prefixes(unit_)
255
+ i_s_units_, conversion_ = next(
256
+ (i_s_units, group[base_unit]) for i_s_units, group in cls.conversion.items() if base_unit in group
257
+ )
258
+ if isinstance(conversion_, tuple):
259
+ factor_, base_ = conversion_
260
+ if i > 0 and base_ != 0:
261
+ raise NotImplementedError("Not supported: unit with non-zero base in denominator")
262
+ else:
263
+ factor_, base_ = conversion_, 0
264
+
265
+ if prefix:
266
+ prefix_multiplier = PREFIX_MULTIPLIERS[prefix]
267
+ # Handle cases where prefix multiplier is brought to a power (e.g area, volume)
268
+ if (
269
+ re.match(i_s_pattern, base_unit)
270
+ and sum(v != 0 for v in i_s_units_.model_dump().values()) == 1
271
+ and abs(pow := next(v for v in i_s_units_.model_dump().values() if v != 0)) > 1
272
+ ):
273
+ prefix_multiplier = prefix_multiplier**pow
274
+
275
+ factor_ *= prefix_multiplier
276
+
277
+ if i == 0:
278
+ i_s_units = i_s_units_
279
+ factor = factor_
280
+ base = base_
281
+ else:
282
+ i_s_units /= i_s_units_
283
+ factor /= factor_
284
+
285
+ return i_s_units, (factor, base), cls.names.get(i_s_units, {}).get("category", "Quantity")
286
+
287
+ @property
288
+ def unit_parts(self) -> dict[ISUnits, str]:
289
+ """Get unit parts."""
290
+ return {self.get_unit_info(part)[0]: part for part in self.unit.split("/")}
291
+
292
+ @field_validator("unit")
293
+ def validate_unit(cls, unit: str) -> str:
294
+ """Validate unit."""
295
+ _ = cls.get_unit_info(unit)
296
+ return unit
297
+
298
+ def _to_default_unit(self) -> float:
299
+ """Convert to default unit."""
300
+ factor, base = self.unit_multiplier
301
+ return self.value * factor + base
302
+
303
+ def _from_default_unit(self, value) -> float:
304
+ """Convert from default unit."""
305
+ factor, base = self.unit_multiplier
306
+ return (value - base) / factor
307
+
308
+ def to(self, unit: str) -> "Quantity":
309
+ """Convert to another unit."""
310
+ if self.get_unit_info(unit)[0] != self.i_s_units:
311
+ self_repr = self.category if self.category != "Quantity" else str(self.unit)
312
+ other_info = self.get_unit_info(unit)
313
+ other_repr = other_info[2] if other_info[2] != "Quantity" else str(unit)
314
+ raise ValueError(f"Cannot convert between different types: {self_repr} <-/-> {other_repr}.")
315
+ default_unit_value = self._to_default_unit()
316
+ factor, base = self.get_unit_info(unit)[1]
317
+ return self.__class__(unit=unit, value=(default_unit_value - base) / factor)
318
+
319
+ def __add__(self, other: Union["Quantity", float, int]) -> "Quantity":
320
+ """Add two quantities, they need to be of the same category."""
321
+ if isinstance(other, float | int):
322
+ return self.__class__(unit=self.unit, value=self.value + other)
323
+
324
+ if other.i_s_units != self.i_s_units:
325
+ raise ValueError("Cannot add quantities of different types.")
326
+
327
+ return self.__class__(
328
+ unit=self.unit,
329
+ value=self._from_default_unit(self._to_default_unit() + other._to_default_unit()),
330
+ )
331
+
332
+ def __sub__(self, other: Union["Quantity", float, int]) -> "Quantity":
333
+ """Add two quantities, they need to be of the same category."""
334
+ if isinstance(other, float | int):
335
+ return self.__class__(unit=self.unit, value=self.value + other)
336
+
337
+ if self.i_s_units != other.i_s_units:
338
+ raise ValueError("Cannot subtract quantities of different types.")
339
+
340
+ return self.__class__(
341
+ unit=self.unit,
342
+ value=self._from_default_unit(self._to_default_unit() - other._to_default_unit()),
343
+ )
344
+
345
+ def _get_output_unit(self, other: Union["Quantity", float, int], out_i_s_units: ISUnits) -> str:
346
+ all_parts = deepcopy(self.unit_parts)
347
+ if isinstance(other, Quantity):
348
+ all_parts |= other.unit_parts
349
+
350
+ if out_i_s_units in all_parts:
351
+ return all_parts[out_i_s_units]
352
+
353
+ unit_parts = next(
354
+ (
355
+ (all_parts.get(i1) or v1["unit"], all_parts.get(i2) or v2["unit"])
356
+ for (i1, v1), (i2, v2) in permutations(self.names.items(), 2)
357
+ if i1 / i2 == out_i_s_units and (i1 in all_parts or i2 in all_parts)
358
+ ),
359
+ None,
360
+ )
361
+
362
+ if unit_parts:
363
+ return "/".join(unit_parts)
364
+
365
+ return None
366
+
367
+ def __mul__(self, other: Union["Quantity", float, int]) -> "Quantity":
368
+ """Multiply a quantity with a number."""
369
+ if isinstance(other, float | int):
370
+ return self.__class__(unit=self.unit, value=self.value * other)
371
+
372
+ i_s_units = self.i_s_units * other.i_s_units
373
+ out = self.__class__(
374
+ value=self._to_default_unit() * other._to_default_unit(),
375
+ unit=self.names.get(i_s_units, {}).get("unit", str(i_s_units)),
376
+ )
377
+ output_unit = self._get_output_unit(other, i_s_units)
378
+ if output_unit is not None:
379
+ out = out.to(output_unit)
380
+ return out
381
+
382
+ def __rmul__(self, other: float | int) -> "Quantity":
383
+ """Multiply a quantity with a number."""
384
+ return self.__mul__(other)
385
+
386
+ def __truediv__(self, other: Union["Quantity", float, int]) -> Union["Quantity", float]:
387
+ """Divide a quantity with a number or another quantity."""
388
+ if isinstance(other, float | int):
389
+ return self.__class__(unit=self.unit, value=self.value / other)
390
+
391
+ i_s_units = self.i_s_units / other.i_s_units
392
+ out = self.__class__(
393
+ value=self._to_default_unit() / other._to_default_unit(),
394
+ unit=self.names.get(i_s_units, {}).get("unit", str(i_s_units)),
395
+ )
396
+ output_unit = self._get_output_unit(other, i_s_units)
397
+ if output_unit is not None:
398
+ out = out.to(output_unit)
399
+ return out
400
+
401
+ def __rtruediv__(self, other: float | int):
402
+ """Divide a number by a quantity."""
403
+ if not isinstance(other, float | int):
404
+ raise TypeError("Can only divide numbers by quantities")
405
+
406
+ i_s_units = self.i_s_units**-1
407
+ return self.__class__(
408
+ value=other / self._to_default_unit(),
409
+ unit=self.names.get(i_s_units, {}).get("unit", str(i_s_units)),
410
+ )
411
+
412
+ def __pow__(self, other: int) -> "Quantity":
413
+ """Raise a quantity to a power."""
414
+ if not isinstance(other, int):
415
+ raise TypeError("Can only raise a quantity to an integer power")
416
+
417
+ i_s_units = self.i_s_units**other
418
+ return self.__class__(
419
+ value=self._to_default_unit() ** other,
420
+ unit=self.names.get(i_s_units, {}).get("unit", str(i_s_units)),
421
+ )
422
+
423
+ def __eq__(self, other: "Quantity") -> bool:
424
+ """Equality."""
425
+ if not isinstance(other, Quantity) or self.i_s_units != other.i_s_units:
426
+ return False
427
+ return self._to_default_unit() == other._to_default_unit()
428
+
429
+ def __neg__(self) -> "Quantity":
430
+ """Negate."""
431
+ return self.__class__(unit=self.unit, value=-self.value)
432
+
433
+ def __repr__(self) -> str:
434
+ """Representation."""
435
+ return f"{self.category}({self})"
436
+
437
+ def __str__(self) -> str:
438
+ """String representation."""
439
+ base = f"{self.value:.3f}" if abs(self.value) >= 1e-2 or self.value == 0 else f"{self.value:.2e}" # noqa: PLR2004
440
+ if "." in base:
441
+ base = base.rstrip("0").rstrip(".")
442
+ return f"{base} {self.unit}" if self.unit else base
443
+
444
+ @classmethod
445
+ def register_unit_rates(
446
+ cls,
447
+ i_s_units: ISUnits | str,
448
+ unit_name: str,
449
+ rate: float = 1.0,
450
+ category: str | None = None,
451
+ ) -> None:
452
+ """Set currency rates."""
453
+ if isinstance(i_s_units, str):
454
+ i_s_units = ISUnits.from_str(i_s_units)
455
+
456
+ if i_s_units not in cls.conversion:
457
+ cls.conversion[i_s_units] = {}
458
+ cls.conversion[i_s_units][unit_name] = rate
459
+ if i_s_units not in cls.names:
460
+ cls.names[i_s_units] = {"category": category, "unit": unit_name}
461
+
462
+ cls.get_unit_info.cache_clear()
@@ -0,0 +1,91 @@
1
+ from datetime import date, time
2
+ from enum import Enum
3
+ from numbers import Number
4
+ from types import UnionType
5
+ from typing import Annotated, Literal, Union, get_args, get_origin
6
+
7
+ from pydantic import BaseModel
8
+ from pydantic.fields import FieldInfo
9
+
10
+ from dash_pydantic_utils.common import get_non_null_annotation, is_subclass
11
+
12
+ SEP = ":"
13
+
14
+
15
+ class Type(Enum):
16
+ """Types of fields."""
17
+
18
+ SCALAR = "scalar"
19
+ LITERAL = "literal"
20
+ MODEL = "model"
21
+ UNKNOWN = "unknown"
22
+ DISCRIMINATED_MODEL = "discriminated_model"
23
+ MODEL_LIST = "model_list"
24
+ SCALAR_LIST = "scalar_list"
25
+ LITERAL_LIST = "literal_list"
26
+ UNKOWN_LIST = "unknown_list"
27
+ DISCRIMINATED_MODEL_LIST = "discriminated_model_list"
28
+ MODEL_DICT = "model_dict"
29
+ SCALAR_DICT = "scalar_dict"
30
+ LITERAL_DICT = "literal_dict"
31
+ UNKOWN_DICT = "unkown_dict"
32
+ DISCRIMINATED_MODEL_DICT = "discriminated_model_dict"
33
+
34
+ @classmethod
35
+ def classify(cls, annotation: type, discriminator: str | None = None, depth: int = 0) -> bool: # noqa: PLR0911, PLR0912
36
+ """Classify a value as a field type."""
37
+ annotation = get_non_null_annotation(annotation)
38
+
39
+ if get_origin(annotation) is Annotated and get_origin(get_args(annotation)[0]) in [Union, UnionType]:
40
+ if discriminator is None:
41
+ discriminator = next(
42
+ (f.discriminator for f in get_args(annotation)[1:] if isinstance(f, FieldInfo)), None
43
+ )
44
+ annotation = get_args(annotation)[0]
45
+
46
+ if is_subclass(annotation, str | Number | bool | date | time):
47
+ return cls.SCALAR
48
+
49
+ if (get_origin(annotation) == Literal) | is_subclass(annotation, Enum):
50
+ return cls.LITERAL
51
+
52
+ if is_subclass(annotation, BaseModel):
53
+ return cls.MODEL
54
+
55
+ if get_origin(annotation) in [Union, UnionType]:
56
+ if discriminator and all(is_subclass(x, BaseModel) for x in get_args(annotation)):
57
+ return cls.DISCRIMINATED_MODEL
58
+ if all(is_subclass(x, str | Number) for x in get_args(annotation)):
59
+ return cls.SCALAR
60
+
61
+ if get_origin(annotation) is list and not depth:
62
+ ann_args = get_args(annotation)
63
+ if not ann_args:
64
+ return cls.UNKOWN_LIST
65
+ args_type = Type.classify(ann_args[0], depth=1)
66
+ if args_type == Type.SCALAR:
67
+ return cls.SCALAR_LIST
68
+ if args_type == Type.LITERAL:
69
+ return cls.LITERAL_LIST
70
+ if args_type == Type.MODEL:
71
+ return cls.MODEL_LIST
72
+ if args_type == Type.DISCRIMINATED_MODEL:
73
+ return cls.DISCRIMINATED_MODEL_LIST
74
+ return cls.UNKOWN_LIST
75
+
76
+ if get_origin(annotation) is dict and not depth:
77
+ ann_args = get_args(annotation)
78
+ if not ann_args:
79
+ return cls.UNKOWN_DICT
80
+ args_type = Type.classify(ann_args[1], depth=1)
81
+ if args_type == Type.SCALAR:
82
+ return cls.SCALAR_DICT
83
+ if args_type == Type.LITERAL:
84
+ return cls.LITERAL_DICT
85
+ if args_type == Type.MODEL:
86
+ return cls.MODEL_DICT
87
+ if args_type == Type.DISCRIMINATED_MODEL:
88
+ return cls.DISCRIMINATED_MODEL_DICT
89
+ return cls.UNKOWN_DICT
90
+
91
+ return cls.UNKNOWN
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: dash-pydantic-utils
3
+ Version: 0.14.0
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'
@@ -0,0 +1,11 @@
1
+ dash_pydantic_utils/__init__.py,sha256=7jzlGgYM7HHEm_M8HzETRTSjj0iHBJdtWiq42n_pO3o,810
2
+ dash_pydantic_utils/common.py,sha256=EFZQQhD93neIVr6amMqU5xVcgNGG-3UwDQ5-OdAfVaY,2151
3
+ dash_pydantic_utils/path.py,sha256=KCSQqUZZ5d14Ph2a-76lCOq-ISvOo2KtTrsW7QNz_ZU,11249
4
+ dash_pydantic_utils/types.py,sha256=9MLmW5Ku5J0MLdv_-uDmZ3E-cL9l-KLN8206P1PczbA,3356
5
+ dash_pydantic_utils/quantity/__init__.py,sha256=cynvB1zP7199Dud7otg9DTbsRXX6L1CvVXOLtlO_USY,281
6
+ dash_pydantic_utils/quantity/pandas.py,sha256=VKUAlsatuqLsF0fcZ_KgJ8k4562KPYfAUAxacCus-ac,10041
7
+ dash_pydantic_utils/quantity/quantity.py,sha256=SbaO3F5V5wWOVUv5bHfMe2IfrCaqsUB7DmD9D3hTVKk,15582
8
+ dash_pydantic_utils-0.14.0.dist-info/METADATA,sha256=_xR1LFZs4jG-D1FETNINTAg7_UanwnbG7XMZ5-kKXjA,1818
9
+ dash_pydantic_utils-0.14.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ dash_pydantic_utils-0.14.0.dist-info/licenses/LICENSE,sha256=j3Flk3DFJo2aHclipGIyVA6PymNGJYbY76qVqrSSogg,1046
11
+ dash_pydantic_utils-0.14.0.dist-info/RECORD,,
@@ -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
@@ -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.