python / python/mypy

TypedDict doesn't support Union[Literal] as key "string literal"

Open
#7,752 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-2-low topic-literal-types topic-typed-dict topic-union-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Possibly bug.
Related: https://github.com/python/mypy/issues/7644

Reproducible example

from typing_extensions import Literal, TypedDict

class TDict(TypedDict):
    KEY1: int
    KEY2: int

d1: TDict = {'KEY1': 1, 'KEY2': 2}

key2: Literal['KEY1']
d2: TDict = {key2: 1, 'KEY2': 2}

key3: Literal['KEY1', 'KEY2']
d3: TDict = {key3: 1, 'KEY2': 2}  # error: Expected TypedDict key to be string literal

I use mypy 0.740 and python3.6

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 provided TypedDict and Literal examples with mypy 0.740, focusing on the d3 assignment that reports “Expected TypedDict key to be string literal.” Done means the reproducible union-of-literals key case is accepted consistently with the single-literal case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.