datafiles icon indicating copy to clipboard operation
datafiles copied to clipboard

Union type is not supported

Open tsuga opened this issue 2 years ago • 3 comments

I'm seeing an error when using Union type.

from typing import Union
from datafiles import datafile, Missing

@datafile("inventory/items/{self.name}.yml")
class InventoryItem:
    """Class for keeping track of an item in inventory."""

    name: str
    unit_price: float
    quantity_on_hand: Union[int, float] = 0

item = InventoryItem("widget", 3)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
[<ipython-input-4-9790d08ed9c3>](https://localhost:8080/#) in <module>()
     10     quantity_on_hand: Union[int, float] = 0.0
     11 
---> 12 item = InventoryItem("widget", 3)

3 frames
[/usr/local/lib/python3.7/dist-packages/datafiles/converters/__init__.py](https://localhost:8080/#) in map_type(cls, name, item_cls)
    134             converter = map_type(cls.__args__[0])
    135             assert len(cls.__args__) == 2
--> 136             assert cls.__args__[1] == type(None)
    137             converter = converter.as_optional()
    138 

AssertionError:

tsuga avatar Jul 28 '22 09:07 tsuga

#239 might be related.

tsuga avatar Jul 28 '22 09:07 tsuga

For classes under your control, Number should work instead of Union[int, float].

How would you expect serialization to work for disparate types such as Union[str, bool, float]?

jacebrowning avatar Jul 28 '22 13:07 jacebrowning

While it's not full support for Union types, https://github.com/jacebrowning/datafiles/pull/272 will handle Union[str, ...] (treated as the broader str type) and Union[int, float] (treated as the broader float type).

jacebrowning avatar Jul 29 '22 22:07 jacebrowning