pydantic-function-models 0.1.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,3 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,7 @@
1
+ from sys import stderr
2
+
3
+ __all__ = ["err"]
4
+
5
+
6
+ def err(*msg) -> None:
7
+ print(*msg, file=stderr)
@@ -0,0 +1,292 @@
1
+ import sys
2
+ from functools import wraps
3
+ from inspect import Parameter, signature
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Any,
7
+ Callable,
8
+ Dict,
9
+ List,
10
+ Mapping,
11
+ Optional,
12
+ Tuple,
13
+ TypeVar,
14
+ get_type_hints,
15
+ overload,
16
+ )
17
+
18
+ from pydantic.alias_generators import to_pascal
19
+ from pydantic.errors import PydanticUserError
20
+ from pydantic.functional_validators import field_validator
21
+ from pydantic.main import BaseModel, create_model
22
+
23
+ __all__ = ("validate_arguments",)
24
+
25
+ assert sys.version_info >= (3, 10), "typing.get_type_hints needs Python 3.10+"
26
+
27
+ if TYPE_CHECKING:
28
+ AnyCallable = Callable[..., Any]
29
+
30
+ AnyCallableT = TypeVar("AnyCallableT", bound=AnyCallable)
31
+
32
+
33
+ @overload
34
+ def validate_arguments(func: None = None) -> Callable[["AnyCallableT"], "AnyCallableT"]:
35
+ ...
36
+
37
+
38
+ @overload
39
+ def validate_arguments(func: "AnyCallableT") -> "AnyCallableT":
40
+ ...
41
+
42
+
43
+ def validate_arguments(func: Optional["AnyCallableT"] = None) -> Any:
44
+ """Decorator to validate the arguments passed to a function."""
45
+
46
+ def validate(_func: "AnyCallable") -> "AnyCallable":
47
+ vd = ValidatedFunction(_func)
48
+
49
+ @wraps(_func)
50
+ def wrapper_function(*args: Any, **kwargs: Any) -> Any:
51
+ return vd.call(*args, **kwargs)
52
+
53
+ wrapper_function.vd = vd # type: ignore
54
+ wrapper_function.validate = vd.init_model_instance # type: ignore
55
+ wrapper_function.raw_function = vd.raw_function # type: ignore
56
+ wrapper_function.model = vd.model # type: ignore
57
+ return wrapper_function
58
+
59
+ if func:
60
+ return validate(func)
61
+ else:
62
+ return validate
63
+
64
+
65
+ ALT_V_ARGS = "v__args"
66
+ ALT_V_KWARGS = "v__kwargs"
67
+ V_POSITIONAL_ONLY_NAME = "v__positional_only"
68
+ V_DUPLICATE_KWARGS = "v__duplicate_kwargs"
69
+
70
+
71
+ class ValidatedFunction:
72
+ def __init__(self, function: "AnyCallable"):
73
+ parameters: Mapping[str, Parameter] = signature(function).parameters
74
+
75
+ if parameters.keys() & {
76
+ ALT_V_ARGS,
77
+ ALT_V_KWARGS,
78
+ V_POSITIONAL_ONLY_NAME,
79
+ V_DUPLICATE_KWARGS,
80
+ }:
81
+ raise PydanticUserError(
82
+ f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
83
+ f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
84
+ code=None,
85
+ )
86
+
87
+ self.raw_function = function
88
+ self.arg_mapping: Dict[int, str] = {}
89
+ self.positional_only_args: set[str] = set()
90
+ self.v_args_name = "args"
91
+ self.v_kwargs_name = "kwargs"
92
+
93
+ type_hints = get_type_hints(function, include_extras=True)
94
+ takes_args = False
95
+ takes_kwargs = False
96
+ fields: Dict[str, Tuple[Any, Any]] = {}
97
+ for i, (name, p) in enumerate(parameters.items()):
98
+ if p.annotation is p.empty:
99
+ annotation = Any
100
+ else:
101
+ annotation = type_hints[name]
102
+
103
+ default = ... if p.default is p.empty else p.default
104
+ if p.kind == Parameter.POSITIONAL_ONLY:
105
+ self.arg_mapping[i] = name
106
+ fields[name] = annotation, default
107
+ fields[V_POSITIONAL_ONLY_NAME] = List[str], None
108
+ self.positional_only_args.add(name)
109
+ elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
110
+ self.arg_mapping[i] = name
111
+ fields[name] = annotation, default
112
+ fields[V_DUPLICATE_KWARGS] = List[str], None
113
+ elif p.kind == Parameter.KEYWORD_ONLY:
114
+ fields[name] = annotation, default
115
+ elif p.kind == Parameter.VAR_POSITIONAL:
116
+ self.v_args_name = name
117
+ fields[name] = Tuple[annotation, ...], None
118
+ takes_args = True
119
+ else:
120
+ assert p.kind == Parameter.VAR_KEYWORD, p.kind
121
+ self.v_kwargs_name = name
122
+ fields[name] = Dict[str, annotation], None # type: ignore[valid-type]
123
+ takes_kwargs = True
124
+
125
+ # these checks avoid a clash between "args" and a field with that name
126
+ if not takes_args and self.v_args_name in fields:
127
+ self.v_args_name = ALT_V_ARGS
128
+
129
+ # same with "kwargs"
130
+ if not takes_kwargs and self.v_kwargs_name in fields:
131
+ self.v_kwargs_name = ALT_V_KWARGS
132
+
133
+ if not takes_args:
134
+ # we add the field so validation below can raise the correct exception
135
+ fields[self.v_args_name] = List[Any], None
136
+
137
+ if not takes_kwargs:
138
+ # same with kwargs
139
+ fields[self.v_kwargs_name] = Dict[Any, Any], None
140
+
141
+ self.create_model(fields, takes_args, takes_kwargs)
142
+
143
+ def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
144
+ values = self.build_values(args, kwargs)
145
+ return self.model(**values)
146
+
147
+ def call(self, *args: Any, **kwargs: Any) -> Any:
148
+ m = self.init_model_instance(*args, **kwargs)
149
+ return self.execute(m)
150
+
151
+ def build_values(
152
+ self,
153
+ args: Tuple[Any, ...],
154
+ kwargs: Dict[str, Any],
155
+ ) -> Dict[str, Any]:
156
+ values: Dict[str, Any] = {}
157
+ if args:
158
+ arg_iter = enumerate(args)
159
+ while True:
160
+ try:
161
+ i, a = next(arg_iter)
162
+ except StopIteration:
163
+ break
164
+ arg_name = self.arg_mapping.get(i)
165
+ if arg_name is not None:
166
+ values[arg_name] = a
167
+ else:
168
+ values[self.v_args_name] = [a] + [a for _, a in arg_iter]
169
+ break
170
+
171
+ var_kwargs: Dict[str, Any] = {}
172
+ wrong_positional_args = []
173
+ duplicate_kwargs = []
174
+ fields_alias = [
175
+ field.alias
176
+ for name, field in self.model.model_fields.items()
177
+ if name not in (self.v_args_name, self.v_kwargs_name)
178
+ ]
179
+ non_var_fields = set(self.model.model_fields) - {
180
+ self.v_args_name,
181
+ self.v_kwargs_name,
182
+ }
183
+ for k, v in kwargs.items():
184
+ if k in non_var_fields or k in fields_alias:
185
+ if k in self.positional_only_args:
186
+ wrong_positional_args.append(k)
187
+ if k in values:
188
+ duplicate_kwargs.append(k)
189
+ values[k] = v
190
+ else:
191
+ var_kwargs[k] = v
192
+
193
+ if var_kwargs:
194
+ values[self.v_kwargs_name] = var_kwargs
195
+ if wrong_positional_args:
196
+ values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
197
+ if duplicate_kwargs:
198
+ values[V_DUPLICATE_KWARGS] = duplicate_kwargs
199
+ return values
200
+
201
+ def execute(self, m: BaseModel) -> Any:
202
+ d = {
203
+ k: v
204
+ for k, v in m.__dict__.items()
205
+ if k in m.__pydantic_fields_set__ or m.model_fields[k].default_factory
206
+ }
207
+ var_kwargs = d.pop(self.v_kwargs_name, {})
208
+
209
+ if self.v_args_name in d:
210
+ args_: List[Any] = []
211
+ in_kwargs = False
212
+ kwargs = {}
213
+ for name, value in d.items():
214
+ if in_kwargs:
215
+ kwargs[name] = value
216
+ elif name == self.v_args_name:
217
+ args_ += value
218
+ in_kwargs = True
219
+ else:
220
+ args_.append(value)
221
+ return self.raw_function(*args_, **kwargs, **var_kwargs)
222
+ elif self.positional_only_args:
223
+ args_ = []
224
+ kwargs = {}
225
+ for name, value in d.items():
226
+ if name in self.positional_only_args:
227
+ args_.append(value)
228
+ else:
229
+ kwargs[name] = value
230
+ return self.raw_function(*args_, **kwargs, **var_kwargs)
231
+ else:
232
+ return self.raw_function(**d, **var_kwargs)
233
+
234
+ def create_model(
235
+ self,
236
+ fields: Dict[str, Any],
237
+ takes_args: bool,
238
+ takes_kwargs: bool,
239
+ ) -> None:
240
+ pos_args = len(self.arg_mapping)
241
+
242
+ class DecoratorBaseModel(BaseModel):
243
+ @field_validator(self.v_args_name, check_fields=False)
244
+ @classmethod
245
+ def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]:
246
+ if takes_args or v is None:
247
+ return v
248
+
249
+ raise TypeError(
250
+ f"{pos_args} positional arguments expected but {pos_args + len(v)} given",
251
+ )
252
+
253
+ @field_validator(self.v_kwargs_name, check_fields=False)
254
+ @classmethod
255
+ def check_kwargs(
256
+ cls,
257
+ v: Optional[Dict[str, Any]],
258
+ ) -> Optional[Dict[str, Any]]:
259
+ if takes_kwargs or v is None:
260
+ return v
261
+
262
+ plural = "" if len(v) == 1 else "s"
263
+ keys = ", ".join(map(repr, v.keys()))
264
+ raise TypeError(f"unexpected keyword argument{plural}: {keys}")
265
+
266
+ @field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
267
+ @classmethod
268
+ def check_positional_only(cls, v: Optional[List[str]]) -> None:
269
+ if v is None:
270
+ return
271
+
272
+ plural = "" if len(v) == 1 else "s"
273
+ keys = ", ".join(map(repr, v))
274
+ raise TypeError(
275
+ f"positional-only argument{plural} passed as keyword argument{plural}: {keys}",
276
+ )
277
+
278
+ @field_validator(V_DUPLICATE_KWARGS, check_fields=False)
279
+ @classmethod
280
+ def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None:
281
+ if v is None:
282
+ return
283
+
284
+ plural = "" if len(v) == 1 else "s"
285
+ keys = ", ".join(map(repr, v))
286
+ raise TypeError(f"multiple values for argument{plural}: {keys}")
287
+
288
+ self.model = create_model(
289
+ to_pascal(self.raw_function.__name__),
290
+ __base__=DecoratorBaseModel,
291
+ **fields,
292
+ )
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.1
2
+ Name: pydantic-function-models
3
+ Version: 0.1.0
4
+ Summary: Migrating v1 Pydantic ValidatedFunction to v2.
5
+ Keywords: pydantic serialization deserialization parsing
6
+ Author-Email: Louis Maddox <louismmx@gmail.com>
7
+ License: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Natural Language :: English
11
+ Classifier: Topic :: Software Development :: Libraries
12
+ Classifier: Framework :: Pydantic
13
+ Classifier: Framework :: Pydantic :: 2
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: pydantic>=2.1.1
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pydantic-function-models
22
+
23
+ Migrating v1 Pydantic ValidatedFunction to v2
24
+
25
+ ![PyPI](https://img.shields.io/pypi/v/pydantic-function-models?logo=python&logoColor=%23cccccc)
26
+ [![pdm-managed](https://img.shields.io/badge/pdm-managed-blueviolet)](https://pdm.fming.dev)
27
+ [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/lmmx/pydantic-function-models/master.svg)](https://results.pre-commit.ci/latest/github/lmmx/pydantic-function-models/master)
28
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/magic-scrape.svg)](https://pypi.org/project/pydantic-function-models)
29
+
30
+ <!-- [![build status](https://github.com/lmmx/pydantic-function-models/actions/workflows/master.yml/badge.svg)](https://github.com/lmmx/pydantic-function-models/actions/workflows/master.yml) -->
@@ -0,0 +1,7 @@
1
+ pydantic_function_models-0.1.0.dist-info/METADATA,sha256=V-CN7c7j8FoX4r2dultBKif_nPsL_D4ra0n1AAkCsSU,1531
2
+ pydantic_function_models-0.1.0.dist-info/WHEEL,sha256=bbAwydobi_oZ_0rI4gBBovxINCqHVHcC26TV6S2A2Io,90
3
+ pydantic_function_models-0.1.0.dist-info/licenses/LICENSE.txt,sha256=G3lig0yYU_DFJj7coAP8MNr-6A-MyNHzke0czVRCsJM,1069
4
+ pydantic_function_models/__init__.py,sha256=C52JK4KMjf9MnPZNJ_yYBD0f49c1qgMV5818fiDNO7Y,58
5
+ pydantic_function_models/log.py,sha256=-TmYMXb1cKLtoTa9cRFhPDua2nnk99WZmPJueriYmwY,96
6
+ pydantic_function_models/validated_function.py,sha256=2FDqwYd3nFYVswdLxdEeln6wXe3b4s-I8w9VDZe4J08,10027
7
+ pydantic_function_models-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.1.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Louis Maddox
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.