The rationale is what the quoted paragraph says. Type checkers don’t track the *value* of expressions, so they don’t have the information needed for the check you desire. Some type checkers may go beyond this and keep track of values, but this is usually not as easy as it would seem from your example, and most code won’t benefit that much, so I don’t blame type checkers that don’t do this. —Guido On Fri, Feb 5, 2021 at 08:03 Vito De Tullio <vito.detullio@gmail.com> wrote:
Hi. Sorry if this is a little bit of a digression, but can I get the chance of a new PEP to ask for a more "strict" check of the optional/required keys of a TypedDict? Looking at the PEP589 I see:
Type checkers may allow reading an item using d['x'] even if the key 'x' is not required, instead of requiring the use of d.get('x') or an explicit 'x' in d check. The rationale is that tracking the existence of keys is difficult to implement in full generality, and that disallowing this could require many changes to existing code.
In fact, I see no error actually raised by current mypy on this snipped of code:
from typing import TypedDict
class _ARequired(TypedDict): required: int
class A(_ARequired, total=False): optional: int
A(required=123).get('required', 456) # no way the fallback value is used A(required=123)['optional'] # KeyError
I'm adding TypedDict in my project as a way to "describe" the response of some external API I consume, so I would really appreciate if I could be "warned" against "dead code" or, worse, risky one.
I'm not sure about the meaning of the rationale I quoted - the problem is in the user codebase checked? Or are internal difficulties of the type checker? In the first case - at least for me - I think that having stricter checks could help showing latent bugs.
FWIW I also think that "total=False" + "Required[...]" is the best syntax, given the backcompatibility with the actual semantic of TypedDict _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: guido@python.org
-- --Guido (mobile)