python / python/mypy

TypedDict item insertion support

Open
#5,359 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

  • Are you reporting a bug, or opening a feature request?
    Feature request
  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
    Currently I can't insert items into TypedDict even after explicit check for a defined key:
from mypy_extensions import TypedDict

GroupDataDict = TypedDict(
    'GroupDataDict', {"children": str,
                      "vars": str,
                      "hosts": str}, total=False
)

test_group: GroupDataDict = {}
key = "children"
if key in ("children", "vars"):
    test_group[key] = "a"

if key not in ["children", "vars"]:
    raise ValueError("")
test_group[key] = "b"

print(test_group)
  • What is the actual behavior/output?
-> % mypy typeddict_insertion.py
typeddict_insertion.py:12: error: TypedDict key must be a string literal; expected one of ('children', 'vars', 'hosts')
typeddict_insertion.py:16: error: TypedDict key must be a string literal; expected one of ('children', 'vars', 'hosts')
  • What is the behavior/output you expect?
    No error
  • What are the versions of mypy and Python you are using?
    mypy 0.620 + Python 3.7
  • Do you see the same issue after installing mypy from Git master?
    I haven't tried
  • What are the mypy flags you are using? (For example --strict-optional)
[mypy]
python_version = 3.7

check_untyped_defs = True
disallow_any_generics = True
disallow_untyped_calls = True
ignore_errors = False
ignore_missing_imports = True
strict_optional = True
warn_unused_ignores = True
warn_redundant_casts = True
warn_unused_configs = True

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

Start by running the supplied TypedDict example with the current mypy version and inspect how TypedDict key expressions are checked. The work is done when explicit checks that restrict a key to valid TypedDict names allow the shown assignments without errors, while invalid keys remain rejected; add or update focused tests for both cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.