Skip to content
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

Teach from_type() to handle TypedDict classes with PEP-655 (Not)Required keys #3339

Closed
Zac-HD opened this issue May 11, 2022 · 1 comment · Fixed by #3344
Closed

Teach from_type() to handle TypedDict classes with PEP-655 (Not)Required keys #3339

Zac-HD opened this issue May 11, 2022 · 1 comment · Fixed by #3344
Labels
enhancement it's not broken, but we want it to be better

Comments

@Zac-HD
Copy link
Member

Zac-HD commented May 11, 2022

PEP-655 defines a better way to mark some keys as required and others as not-required on the TypedDict class - before, you had to define a parent class with some keys and a child class with others. We should upgrade our resolver code to handle this, and write test cases for both pure-new-style and mixes of inheritance-based (old) and (Not)Required-based (new) styles.

if (
hasattr(typing, "_TypedDictMeta")
and type(thing) is typing._TypedDictMeta # type: ignore
or hasattr(types.typing_extensions, "_TypedDictMeta") # type: ignore
and type(thing) is types.typing_extensions._TypedDictMeta # type: ignore
): # pragma: no cover
# The __optional_keys__ attribute may or may not be present, but if there's no
# way to tell and we just have to assume that everything is required.
# See https://github.com/python/cpython/pull/17214 for details.
optional = getattr(thing, "__optional_keys__", ())
anns = {k: from_type(v) for k, v in get_type_hints(thing).items()}
if (
(not anns)
and thing.__annotations__
and ".<locals>." in getattr(thing, "__qualname__", "")
):
raise InvalidArgument("Failed to retrieve type annotations for local type")
return fixed_dictionaries( # type: ignore
mapping={k: v for k, v in anns.items() if k not in optional},
optional={k: v for k, v in anns.items() if k in optional},
)

Prior work on recent types: #3331, #3280, #2978.

@Zac-HD Zac-HD added the enhancement it's not broken, but we want it to be better label May 11, 2022
@Cheukting
Copy link
Contributor

I will give this a try as well @Zac-HD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement it's not broken, but we want it to be better
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants