python / python/mypy

`.get(key)` should narrow final TypedDicts

Open
#17,087 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

in keyword narrowing was implemented for TypedDicts, but not .get(). I understand that it may be hard to implement for arbitrary default arguments of .get(key, default), but the .get(key) variable, without a default value, can be useful as well.

Bug Report

To Reproduce

import typing


@typing.final
class Node(typing.TypedDict):
    name: str
    children: list[typing.Union['Node', 'Leaf']]


@typing.final
class Leaf(typing.TypedDict):
    name: str


x: Node | Leaf


### INCORRECT ERROR
if x.get('children'):
    x['children']  # error: TypedDict "Leaf" has no key "children"


### CORRECT
if 'children' in x:
    x['children']

Expected Behavior

No error

Actual Behavior

error: TypedDict "Leaf" has no key "children"  [typeddict-item]

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: non
  • Mypy configuration options from mypy.ini (and other config files):
warn_redundant_casts = True
warn_unused_ignores = True
warn_no_return = False
warn_return_any = True
disallow_untyped_defs = True
disallow_any_generics = True
  • Python version used:
    Python 3.12.1

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 Python reproduction and locating the existing TypedDict narrowing behavior for the in operator. No source file or test is named in the report; done means that the .get('children') check narrows x so the subsequent x['children'] produces no error, while the default-argument case remains scoped separately.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.