mitsuse / typedjson-python

JSON decoding for Python with type hinting (PEP 484).
MIT License
29 stars 5 forks source link

Support heterogeneous lists #2

Closed ghost closed 5 years ago

mitsuse commented 5 years ago

@rruc List[T], where T is defined by TyprVar(‘T’, int, str), can be List[str] or List[int]. It is not List[Union[int, str]], so List[T] should not accept [0, 'foo']. The feature can be archived with ‘List[Union[int, str]]’ suggested in this pull-req.

ghost commented 5 years ago

@mitsuse you are right, I think it would be better to add these test cases to the tests though, like it has been done for the Tuple type:

def test_can_decode_heterogeneous_list() -> None:
    json = [1, 'foo']
    assert typedjson.decode(List[Union[int,str]], json) == json

def test_cannot_decode_homogeneous_list_with_incompatible() -> None:
      json = [1, 2, 3]
     assert isinstance(typedjson.decode(List[str], json), typedjson.DecodingError)

 def test_cannot_decode_heterogeneous_list_with_incompatible() -> None:
     json = [1, 'foo']
     assert isinstance(typedjson.decode(List[Union[str,str]], json), typedjson.DecodingError)        

Moreover, should we consider the case of constrained typed variable lists? i.e., typedjson.decode(List[T], json) where T = TypeVar('T', int, str) and json = ['foo'] or json = [5] should be decoded as json but right now it gives an error.

mitsuse commented 5 years ago

@rruc

I think it would be better to add these test cases to the tests though, like it has been done for the Tuple type:

OK, please submit a new pull-request about this if you have time.

Moreover, should we consider the case of constrained typed variable lists?

Unfortunately, we cannot know what is a type specified as TypeVar T at runtime, so it should raise DecodingError always.

ghost commented 5 years ago

@rruc

I think it would be better to add these test cases to the tests though, like it has been done for the Tuple type:

OK, please submit a new pull-request about this if you have time.

Moreover, should we consider the case of constrained typed variable lists?

Unfortunately, we cannot know what is a type specified as TypeVar T at runtime, so it should raise DecodingError always.

I've submitted a new pull request with the new test cases specified above. I'm going to close this pull request now, bye.