22 ms·
You can't even represent `Json` in Python's type system because it would require a recursive type. edit: I think this is actually a Python type annotation limi
by insanitybit 3y ago
You can't even represent `Json` in Python's type system because it would require a recursive type.
edit: I think this is actually a Python type annotation limitation but it's possible that's mypy, although I think in 99% of cases those are fine to conflate (I have used other Python type systems).
- dazzlefruit 3y agoIn VSCode (which uses PyRight/PyLance) and Python 3.10: JSONObject = None | str | int | bool | list["JSONObject"] | dict[str, "JSONObject"] # this type checks a: JSONObject = {"a": [1, 2, "7", True, {"false": None}]} # this doesn't type check b: JSONObject = {"a": [1, 2, "7", True, {"false": object()}]}
- insanitybit 3y agoCool, guess they finally fixed this. Must've been in the last ~1 year, give or take. Of course, it relies on quoting your types, which is... a matter of taste, I suppose.
- dazzlefruit 3y agoQuoting types that are defined later is a wart but it's not very bad. VSCode's UI will happily handle it as if the quotes weren't there.
- npage97 3y agoYou can also use from __future__ import annotations so the quotes become unnecessary. https://peps.python.org/pep-0563/ https://peps.python.org/pep-0563/
- insanitybit 3y agoDoes that work with recursive types? I have had mixed results with `from __future__ import annotations` personally, but I haven't written much Python in ~a year or so.
- deleted 3y ago[deleted]
- FreakLegion 3y agoIt's worked for many years, but you won't often see it used outside of class definitions because all of the other tools struggle with it (Pylint, Flake8, Pylance, etc. spit out some variation of an undefined variable error).
- insanitybit 3y agoI don't think it has worked for years. I had used that same exact __annotations__ and my recollection was that recursive types still did not work.
- FreakLegion 3y agoIt's worked for years. I've been using it the whole time.
- corethree 3y agoYou can. from typing import Dict, List JSON = Dict[str, 'JSON'] | List['JSON'] | float | int | str | None I would say the only thing ugly here is the string 'JSON' that is used for recursion. From a static safety perspective with an external type checker the static safety effect is identical.