Improve JSON typing by including Mapping/Sequence variants.
Review Request #13125 — Created June 26, 2023 and submitted
The new JSON typing introduced in Djblets 3.3 worked fine if exclusively
working withJSONValue,JSONDict,JSONList, or simple primitives
(likeintorbool). However, trying to assign an
otherwise-compatibleDictorList(such as aDict[str, str]or
List[int]) would result in typing errors.This was due to the mutability of the type. A
Dict[str, str], for
example, cannot be assigned as aJSONDict, because aJSONDictshould
be able to set anyJSONValueas a value, and that would violate the
type of aDict[str, str]. Same with lists.The solution to this is to accept a
MappingandSequence. These are
both immutable types, and from a typing perspective, there's no risk to
storing the wrong value there. In part, this is because we already can't
deeply key into a nestedJSONDictwithout casting at each level
anyway, since a value could be any supported JSON type. So once we've
stored it, it's up to the callers to validate types anyway (and at this
complexity, we're wanting to represent structures asTypedDicts and/or
sanity-check values).The new
JSONDictImmutableandJSONListImmutableprovide this typing
option. They're part of theJSONValueunion, allowing type checkers to
check against them when assigning aDictor aList.Going forward, we'll want to aim to use
Mapping,Sequence,
Iterable, and other more generic immutable types overDictand
Listany time we're accepting a value we don't plan to modify, to
avoid the sort of problems we've uncovered with ourJSONtypes.
Encountered this issue with in-progress code. Verified that the this
addressed all issues.Played around a fair amount with creating and typing deeply-nested
JSON data from dicts and lists containing compatible values, and
verified that pyright and mypy were happy.
| Summary | ID |
|---|---|
| 00b4c4f1ee8599627157a40c90a76bf6b96e7566 |