
A quick note on some text on the PEP (below): On Sat, 27 Feb 2021 at 03:09, David Foster <davidfstr@gmail.com> wrote:
[snip]
Rejected Ideas
==============
Special syntax around the *key* of a TypedDict item ---------------------------------------------------
::
class MyThing(TypedDict): opt1?: str # may not exist, but if exists, value is string opt2: Optional[str] # always exists, but may have null value
or:
::
class MyThing(TypedDict): Optional[opt1]: str # may not exist, but if exists, value is string opt2: Optional[str] # always exists, but may have null value
These syntaxes would require Python grammar changes and it is not believed that marking TypedDict items as required or potentially-missing would meet the high bar required to make such grammar changes.
Also, “let’s just not put funny syntax before the colon.” [1]_
This is factually wrong for the second example; 'Optional[opt1]: str' is perfectly valid Python syntax right now. It will most likely break at runtime with a NameError because it requires opt1 to be defined, but it does not require a grammar change. I guess someone could even argue for Optional["opt1"]: str (which is in some way more accurate given that the key is the string "opt1") which would be implementable at a library level, so perhaps this part of the PEP needs rephrasing. To avoid misunderstanding: this is a comment on the correctness of the PEP text, but I am NOT advocating for this Optional[key]: type syntax, I'm personally happy with the proposal as it is, thanks for writing this :) Best, D.