facebook / pyre-check

Performant type-checking for python.
https://pyre-check.org/
MIT License
6.84k stars 437 forks source link

pyre_extensions.safe_json does not work with typed dictionaries #539

Open Trolldemorted opened 2 years ago

Trolldemorted commented 2 years ago

I tried to recreate your safe_json typed dictionaries example from your readme, but it doesn't work:

from pyre_extensions import safe_json
from typing import Dict, List, TypedDict

class Movie(TypedDict):
    name: str
    year: int

safe_json.loads('{"name": "Blade Runner", "year": 1982 }', Movie)

throws instead of successfully parsing the input into an instance of Movie:

Traceback (most recent call last):
  File "[...]/.venv/lib/python3.8/site-packages/pyre_extensions/safe_json.py", line 116, in loads
    _validate_value(parsed, target)
  File "[...]/.venv/lib/python3.8/site-packages/pyre_extensions/safe_json.py", line 95, in _validate_value
    raise InvalidJson(f"Invalid value type {target_type}")
pyre_extensions.safe_json.InvalidJson: Invalid value type <class '__main__.Movie'>: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "models.py", line 8, in <module>
    safe_json.loads('{"name": "Blade Runner", "year": 1982 }', Movie)
  File "[...]/.venv/lib/python3.8/site-packages/pyre_extensions/safe_json.py", line 119, in loads
    raise InvalidJson(str(exception))
pyre_extensions.safe_json.InvalidJson: Invalid value type <class '__main__.Movie'>: line 1 column 1 (char 0): line 1 column 1 (char 0)

The code was executed in a fresh virtualenv (CPython3.8.10.final.0-64) that executed pip3 install pyre_extensions:

$ pip3 freeze
mypy-extensions==0.4.3
pyre-extensions==0.0.23
typing-inspect==0.7.1
typing_extensions==4.0.0
grievejia commented 2 years ago

cc. @pradeep90

grievejia commented 2 years ago

@Trolldemorted Actually, I think this is only a problem for Python<=3.8. One workaround for pre-3.9 Python is to import TypedDict from typing_extensions instead.