Skip to content

.get(key) should narrow final TypedDicts #17087

Open
@roganov

Description

@roganov

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions