front.py2pydantic¶
How do we eliminate some of the boilerplate between having python functions and making them pydantic?
>>> from i2.tests.objects_for_testing import formula1
>>> pyd_input_model = func_to_pyd_input_model_cls(formula1)
>>> pyd_input_model
<class 'pydantic.main.formula1'>
>>> from i2 import Sig
>>> Sig(formula1)
<Sig (w, /, x: float, y=1, *, z: int = 1)>
>>> Sig(pyd_input_model)
<Sig (*, w: Any, x: float, z: int = 1, y: int = 1) -> None>
>>> pyd_func = func_to_pyd_func(formula1)
>>> input_model_instance = pyd_input_model(w=1, x=2)
>>> input_model_instance
formula1(w=1, x=2.0, z=1, y=1)
>>> pyd_func(input_model_instance)
3.0
>>> formula1(1, x=2) # can't say w=1 because w is position only
3
-
front.py2pydantic.
func_to_pyd_func
(func: Callable, dflt_type=typing.Any)[source]¶ Get a ‘opyrator’ function from a python function. That is, a function that has a single pydantic model input and output.
-
front.py2pydantic.
func_to_pyd_input_model_cls
(func: Callable, dflt_type=typing.Any, *, name=None, warn_when_changing_names=True)[source]¶ Get a pydantic model of the arguments of a python function
>>> def foo(a, b: int, c: bool=False): ... ... >>> obj = func_to_pyd_input_model_cls(foo) >>> import json >>> assert json.loads(obj.schema_json()) == ( ... { ... 'title': 'foo', ... 'type': 'object', ... 'properties': { ... 'a': {'title': 'A'}, ... 'b': {'title': 'B', 'type': 'integer'}, ... 'c': {'title': 'C', 'default': False, 'type': 'boolean'} ... }, ... 'required': ['a', 'b'] ... })
If some argument names of the function conflict with attribute names of BaseModel, these will be capitalized to resolve the conflict.
>>> def bar(x, copy, schema): ... ... >>> obj2 = func_to_pyd_input_model_cls(bar, warn_when_changing_names=False) >>> assert json.loads(obj2.schema_json()) == ( ... { ... 'title': 'bar', ... 'type': 'object', ... 'properties': { ... 'x': {'title': 'X'}, ... 'COPY': {'title': 'Copy'}, ... 'SCHEMA': {'title': 'Schema'}}, ... 'required': ['x', 'COPY', 'SCHEMA'] ... })