Skip to content

Commit

Permalink
add putting_together example to tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
zhPavel committed Feb 9, 2024
1 parent 8646fc1 commit 48f041a
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/conversion/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,11 @@ the second parameter is the pointing to the field of the destination model,
the third parameter is the function that casts source data to the destination type.

Usually, only field types are used as predicates here.


Putting together
===================

Let's explore complex example collecting all features together.

.. literalinclude:: /examples/conversion/tutorial/putting_together.py
72 changes: 72 additions & 0 deletions docs/examples/conversion/tutorial/putting_together.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# mypy: disable-error-code="empty-body"
from dataclasses import dataclass
from datetime import date
from uuid import UUID

from adaptix import P
from adaptix.conversion import bind, coercer, impl_converter


@dataclass
class Author:
name: str
surname: str
birthday: date # is converted to str


@dataclass
class Book:
id: UUID # is converted to str
title: str
author: Author # is renamed to `writer`
isbn: str # this field is ignored


@dataclass
class AuthorDTO:
name: str
surname: str
birthday: str


@dataclass
class BookDTO:
id: str
title: str
writer: AuthorDTO
page_count: int # is taken from `pages_len` param
rating: float # is taken from param with the same name


@impl_converter(
recipe=[
bind('pages_len', 'page_count'),
bind(P[Book].author, P[BookDTO].writer),
coercer(UUID, str, func=str),
coercer(P[Author].birthday, P[AuthorDTO].birthday, date.isoformat),
]
)
def convert_book_to_dto(book: Book, pages_len: int, rating: float) -> BookDTO:
...


assert (
convert_book_to_dto(
book=Book(
id=UUID('87000388-94e6-49a4-b51b-320e38577bd9'),
isbn='978-0-7432-4722-1',
title="Fahrenheit 451",
author=Author(name="Ray", surname="Bradbury", birthday=date(1920, 7, 22)),
),
pages_len=158,
rating=4.8,
)
==
BookDTO(
id='87000388-94e6-49a4-b51b-320e38577bd9',
title="Fahrenheit 451",
writer=AuthorDTO(name="Ray", surname="Bradbury", birthday='1920-07-22'),
page_count=158,
rating=4.8,
)
)

0 comments on commit 48f041a

Please sign in to comment.