Skip to content

PEP 655 Add interaction with __required_keys__, __optional_keys__ and get_type_hints() #1057

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 11, 2022

Conversation

d-k-bo
Copy link
Contributor

@d-k-bo d-k-bo commented Feb 6, 2022

The current implementation of PEP 655 doesn't implement all specified features of the current draft:

  • Required and NotRequired don't interact with __required_keys__ and __optional_keys__
  • get_type_hints() doesn't strip out Required nor NotRequired (by default)

Implementing the first aspect requires modifying _TypedDictMeta, which breaks backward compatibility when using typing's is_typeddict() on typing_extensions' TypedDict:

import typing

import typing_extensions


class Movie(typing_extensions.TypedDict):
    title: str
    year: typing_extensions.NotRequired[int]


typing_extensions.is_typeddict(Movie)  # True
typing.is_typeddict(Movie)  # False

For example this PR breaks the current version of typeguard when using typing_extension.TypedDict on a recent version of python.

This is my first contribution, so please point out if I missed any required steps before opening a PR.

Change TypedDict to respect keys that are marked as Required
or NotRequired (requires PEP 560).
Make TypedDict and is_typeddict accessible if typing
doesn't implement Required.
Replace _strip_annotations() with _strip_extras() to strip Annotated, Required
and NotRequired.
Change get_type_hints() to pass include_extras=True to newer versions of
typing.get_type_hints() and use _strip_extras().
Make get_type_hints accessible if typing
doesn't implement Required.
Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thank you!

cc @davidfstr in case you also want to take a look

Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add an entry to the CHANGELOG file? (Sorry, just noticed this.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants