On Sun, Mar 7, 2021 at 5:02 PM Eric Traut <eric@traut.com> wrote:
I noticed that mypy does not flag x['fieldB'] as an error even though the field is potentially not present. I presume that code should always use the `get` method when attempting to access such fields. I'm curious why the TypedDict support in mypy doesn't emit an error in this case. Was that an oversight, or perhaps there was there a concern about generating false positives?

We decided to allow x['field'] to avoid false positives when annotating legacy code. We've seen code that first checks whether a key exists and then uses x[...], and various variants of this where a technically non-required key is always present. Also users tend to just use total=False even if some keys are always present, because currently it's tedious to mark a subset of keys as not required. Users may then access the implicitly required keys using x[...], and there may even not be a reasonable default to use with get().
My inclination is to always emit an error when code attempts to access a non-required TypedDict field using a subscript. Thoughts?

This would probably cause quite a few false positives in some existing codebases, but it could be nice for new code, at least once it's easier to declare a subset of keys as non-required. In mypy we'd probably add a strictness flag to enable this.