On Tue, Mar 9, 2021 at 8:05 AM Jukka Lehtosalo email@example.com wrote:
On Sun, Mar 7, 2021 at 5:02 PM Eric Traut firstname.lastname@example.org 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().
Were any of those variants of a dynamic nature, or were those patterns only checking a static field. I mean:
if 'some_key' in typed_dict: ...typed_dict['some_key']
if check_keys(typed_dict, keys): ...typed_dict[k] # k in keys
I'm asking because in the first case you could use the in expression as a "narrowing"-like guard. Having inside the if a TypedDict with the same fields, but some_key being a required one.
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.
Jukka _______________________________________________ Typing-sig mailing list -- email@example.com To unsubscribe send an email to firstname.lastname@example.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: email@example.com