python / python/mypy

Disallow x["foo"] for NotRequired TypedDict access

Open
#12,094 8 comments 29 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-typed-dict
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

After PEP 655 was implemented, mypy now checks initialization of typed dicts. Access to these dicts however is not checked for required/optional.

Pitch

We have lots of code which makes use of TypedDict with optional parameters, and one of the most common coding errors is to call dict_value["param"]. Because these are not required keys, a sound type checker should disallow this access and instead require dict_value.get("param").

This problem was mentioned near the end of #2632 but no subsequent ticket was filed.

I intend to have a PR for this up in the next few minutes.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files or tests are named. Start with PEP 655 and the discussion in #2632, then trace mypy's TypedDict access checking; done means access to a NotRequired key is rejected while the issue's suggested get() alternative remains valid.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.