chili
chili copied to clipboard
typing.Optional seems to be required for optional fields (while README implies otherwise)
I actually managed to work around this issue, but just to notify you there seems to be some incorrect parts in the README docs. And to share some suggestions. I could make a pull request for both but I'm not sure what your thoughts are about it.
Edit: I just noticed it's possible to do what I want with dataclasses and chili.decoder import ClassDecoder
(or just chili.decode()
directly), as is shown in https://github.com/kodemore/chili/blob/main/tests/usecases/dataclasses_test.py#L140-L147
Which is perfect for my use case.
Below my original message, which could still be interesting:
When I try to decode a dict to a class while omitting a field that does have a default defined, I get a chili.error.DecoderError@missing_property
For example when I run the example straight from the README:
from typing import List
from chili import Decoder, decodable
@decodable
class Book:
name: str
author: str
isbn: str = "1234567890"
tags: List[str] = []
book_data = {"name": "The Hobbit", "author": "J.R.R. Tolkien"}
decoder = Decoder[Book]()
book = decoder.decode(book_data)
I get: chili.error.DecoderError@missing_property: key=isbn
I noticed in this unit test the optional fields are typed with Optional[SomeType]
, which indeed fixes the issue.
Although this seems to make sense at first given the name "Optional", it does make it possible to set the field to None
, which might not always be as intended. A custom decoder could be used to parse 'None' to the default value, although it would be a bit more convenient if this would be done automatically by specifying a default while leaving out Optional
.
Besides, it would be nice to be able to use the more recent SomeType | None
syntax as an alternative to Optional[SomeType]
.
I also noticed that @encodable
& @decodable
seem to be redundant (or at least in the cases from the examples), making it possible to keep most parts of the code completely unaware of the chili lib, which I like a lot 👍