python / python/mypy

Typeguard for TypedDict keys

Open
#11,553 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

I don't know enough to say whether this is a mypy request or a typing module request... but I find myself doing this pattern to avoid the error TypedDict key must be a string literal; expected one of ("a", "b") [misc]

class MyDict(TypedDict, total=False):
    a: int
    b: str
    ...

MyDictKeys = Union[Literal['a'], Literal['b']]

def is_mydict_key(key: str) -> TypeGuard[WidgetOptionKeys]:
    return key in MyDictKeys.__annotations__

Pitch

not sure how it would be implemented (or if it already is!) ... but it would be nice to have a way to type narrow a key without having to duplicate all of the keys in a TypedDict in a separate Union of Literals

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 determining whether this belongs in mypy or the typing module, then investigate how TypedDict key checking and TypeGuard interact. Compare the current duplicate Literal-union workaround with possible key narrowing approaches. Done means a supported way to narrow a TypedDict key without separately duplicating its keys.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.