Skip to content

Commit

Permalink
Merge pull request #9 from lu-pl/lupl/readme_init_model_from_kwargs
Browse files Browse the repository at this point in the history
docs: Add description + example for init_model_from_kwargs
  • Loading branch information
lu-pl authored Jul 25, 2024
2 parents fe25068 + 450dd4c commit 3644e31
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ print(foo.method(2, 3)) # 6
print(foo.route.method(2, 3)) # 13
```

## CurryModel
## Pydantic Tools

### CurryModel
The CurryModel constructor allows to sequentially initialize (curry) a Pydantic model.

```python
Expand Down Expand Up @@ -64,3 +66,39 @@ curried_model_3 = CurryModel(MyModel)
model_instance_3 = curried_model_3(x="1", y=2)(z=("3", 4))
print(model_instance_3)
```

### init_model_from_kwargs

The `init_model_from_kwargs` constructor allows to initialize (potentially nested) models from (flat) kwargs.

```python
class SimpleModel(BaseModel):
x: int
y: int = 3


class NestedModel(BaseModel):
a: str
b: SimpleModel


class ComplexModel(BaseModel):
p: str
q: NestedModel


# p='p value' q=NestedModel(a='a value', b=SimpleModel(x=1, y=2))
model_instance_1 = init_model_from_kwargs(
ComplexModel, x=1, y=2, a="a value", p="p value"
)

# p='p value' q=NestedModel(a='a value', b=SimpleModel(x=1, y=3))
model_instance_2 = init_model_from_kwargs(
ComplexModel, p="p value", q=NestedModel(a="a value", b=SimpleModel(x=1))
)

# p='p value' q=NestedModel(a='a value', b=SimpleModel(x=1, y=3))
model_instance_3 = init_model_from_kwargs(
ComplexModel, p="p value", q=init_model_from_kwargs(NestedModel, a="a value", x=1)
)
```
2 changes: 1 addition & 1 deletion tests/tests_pydantic_tools/test_init_model_from_kwargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from tests.data.init_model_from_kwargs_parameters import (
init_model_from_kwargs_parameters,
)
from upto.pydantic_tools.model_constructors import init_model_from_kwargs
from upto import init_model_from_kwargs


@pytest.mark.parametrize(("model", "kwargs"), init_model_from_kwargs_parameters)
Expand Down
1 change: 1 addition & 0 deletions upto/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from upto.compose_router import ComposeRouter
from upto.pydantic_tools.curry_model import CurryModel
from upto.pydantic_tools.model_constructors import init_model_from_kwargs

0 comments on commit 3644e31

Please sign in to comment.