Skip to content

Proposal: Workaround for mypy's incorrect implementation of NotRequired #483

@untitaker

Description

@untitaker

We have a schema definition with two fields, foo_required and foo_optional.

{"properties": {"foo_required": {}, "foo_optional": {}}, "required": ["foo_required"]}

Now consider this code:

x["foo_optional"]

VSCode/pyright does error on the above line because it might crash. Unfortunately, mypy does not.

This issue is tracked in python/mypy#12094 -- unfortunately the issue is open for more than a year.

In a comment I came up with an idea for a workaround where we actually construct multiple TypedDicts and combine them with a Union. This contraption will also cause mypy to find the problem in the above code snippet.

class MyDict(TypedDict, total=False):
    foo_required: Required[int]
    foo_optional: NotRequired[int]


class MinimalDict(TypedDict, total=False):
    foo_required: Required[int]

MyDict2 = Union[MyDict, MinimalDict]

Do you think this would be reasonable to emit by default from jsonschema-gentypes? Or is it too hacky?

We are also considering running pyright in CI to catch those errors, but it would be a bigger project for us.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions