This problem arose from trying to type the environ argument for a WSGI application. There are specific keys of the environ dict that have non-str types, and then all the other keys are HTTP_ variables (or server-defined variables, which can be ignored for this purpose) with type str (or Text, depending on the version of Python).
I would like to get stronger typing on environ than Dict[str, Any], but there isn't a way to do that with TypedDict currently because the set of possible keys is unbounded (the client can send any HTTP header).
Ideally, I'd like to be able to do something like:
EnvironDict = TypedDict("EnvironDict", {
"wsgi.version": Tuple[int, int],
"wsgi.input": IO[str],
# ...
}, default_type=str, total=False)
and have this mean that any key is allowed in the dictionary and all unknown keys get a value type of str.
Thanks for the proposal! Unfortunately, I don't think we will have time to work on this in short term, but we may raise priority if this request will appear again.
Also a random note: same functionality is available for protocols using __getattr__().
We'd need a way to represent this using the class-based syntax as well.
In class-based syntax this could plausibly be supported as:
class EnvironDict(TypedDict, total=False, default_type=str):
version: Tuple[int, int]
I have a usecase this would be extremely helpful for as well, in the context of a physical modeling app. We have EXTREMELY large dictionaries of physical properties passed to models. They're mostly floating point measurements except for a small minority of values that are strings or nested dicts. Using a default type of float and only specifying the exceptions could improve concision by hundreds of lines.
Please make this happen
Most helpful comment
Please make this happen