mitsuse / typedjson-python

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

Decoding None as some iterable types raises runtime error #11

Closed ganow closed 3 years ago

ganow commented 3 years ago

Hi, thank you for providing a great package! I found that when we try to decode None as List[str], typedjson.decode() raises a runtime error. I think this behavior is unexpected and typedjson.decode() should return either the TypeMismatch error or the decoded result with an empty list.

$ cat example.py
from typing import List
import typedjson

json = None
print(typedjson.decode(List[str], json))

$ poetry run python example.py
Traceback (most recent call last):
  File "example.py", line 5, in <module>
    print(typedjson.decode(List[str], json))
  File "/Users/ny/local/src/github.com/mitsuse/typedjson-python/typedjson/decoding.py", line 90, in decode
    result = d(type_, json, path)
  File "/Users/ny/local/src/github.com/mitsuse/typedjson-python/typedjson/decoding.py", line 225, in decode_as_list
    for index, element in enumerate(json):
TypeError: 'NoneType' object is not iterable

This behavior can be problematic in situations such as the following: if we are expecting some list and no key for that list is given.

@dataclass(frozen=True)
class Person:
    name: str
    skills: List[str]

data = {'name': 'Taro', 'skill': ['C', 'Python']}  # the key specification of the received input has a typo.
person = typedjson.decode(Person, data)  # raises a runtime error!