I would like to raise a different issue that we might want to address in PEP 764, as per @erictraut‘s comment from 2023, one which hasn’t been discussed so far(?): The ability to infer the TypedDict
type for a “constant” dictionary. Consider the following snippet in TypeScript:
const someObj = {
a: 1,
b: 2,
} as const; // type inferred as `{ a: 1, b: 2 }`
We might want a similar mechanism in Python (provided some version of PEP 764 ends up being accepted), which automatically infers an anonymous/inline TypedDict type for the given variable. This would be very convenient for dictionaries you create only in a single place in your application, as you wouldn’t need to repeat the structure of the data twice (once as data, once as type). The latter is particularly annoying when writing complex nested dictionary structures, a use case that PEP 764 is trying to address. Should such a mechanism therefore be included in PEP 764?
Either way, I’m not sure how one would best implement this (short of introducing new syntax).
Maybe as an annotation?
from typing import InferConst
SOME_CONST_DICT: InferConst = {
"a": 1,
"b": 2
} # inferred as closed TypedDict[{ "a": Literal[1], "b": Literal[2] }]
Or as a function in typing
?
from typing import infer_const
SOME_CONST_DICT = infer_const({
"a": 1,
"b": 2
}) # inferred as closed TypedDict[{ "a": Literal[1], "b": Literal[2] }]
Any other good options?
(Note that I’m a being a bit cavalier about what “const” means. This would of course still need to be sorted out.)