Skip to content

Feature request: option for strict TypedDict __getitem__ #6483

Closed
@ariebovenberg

Description

@ariebovenberg

TypedDict is really useful for expressing data with a consistent shape, but where not all fields are present.
I feel it can be improved by adding a "strict" mode for accessing items. This way, mypy can enforce that the proper checks are made.

An example to illustrate:

from mypy_extensions import TypedDict

class FooBase(TypedDict):
    x: int  # a required field

class Foo(FooBase, total=False):
    y: int  # an optional field

f = Foo(x=5)

# current situation
f['x']  # ok
f['y']  # ok
f.get('y', 0)  # ok

# "strict" situation
f['x']  # ok (item is always present)
f['y']  # FAIL
f.get('y', 0)  # ok (explicit fallback is needed)

I understand that not everyone wants this behavior, so perhaps it would be useful as a strictness flag?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions