Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 138
Add support for PEP 705#284
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
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5081932
Add support for PEP 705
JelleZijlstra 3192691
formatting
JelleZijlstra f884301
Merge branch 'main' into pep705
JelleZijlstra c137ccd
only ReadOnly
JelleZijlstra 7c781d5
Code review fixes
JelleZijlstra d223307
Fix 3.13
JelleZijlstra e865252
Apply suggestions from code review
JelleZijlstra 597c07a
Update src/test_typing_extensions.py
JelleZijlstra deb966d
Apply suggestions from code review
JelleZijlstra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -86,6 +86,7 @@ | ||
| 'TYPE_CHECKING', | ||
| 'Never', | ||
| 'NoReturn', | ||
| 'ReadOnly', | ||
| 'Required', | ||
| 'NotRequired', | ||
| @@ -768,7 +769,7 @@ def inner(func): | ||
| return inner | ||
| if sys.version_info >= (3, 13): | ||
| if hasattr(typing, "ReadOnly"): | ||
| # The standard library TypedDict in Python 3.8 does not store runtime information | ||
| # about which (if any) keys are optional. See https://bugs.python.org/issue38834 | ||
| # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" | ||
| @@ -779,15 +780,37 @@ def inner(func): | ||
| # Aaaand on 3.12 we add __orig_bases__ to TypedDict | ||
| # to enable better runtime introspection. | ||
| # On 3.13 we deprecate some odd ways of creating TypedDicts. | ||
| # PEP 705 proposes adding the ReadOnly[] qualifier. | ||
| TypedDict = typing.TypedDict | ||
| _TypedDictMeta = typing._TypedDictMeta | ||
| is_typeddict = typing.is_typeddict | ||
| else: | ||
| # 3.10.0 and later | ||
| _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters | ||
| def _get_typeddict_qualifiers(annotation_type): | ||
| while True: | ||
| annotation_origin = get_origin(annotation_type) | ||
| if annotation_origin is Annotated: | ||
| annotation_args = get_args(annotation_type) | ||
| if annotation_args: | ||
| annotation_type = annotation_args[0] | ||
| else: | ||
| break | ||
| elif annotation_origin is Required: | ||
| yield Required | ||
| annotation_type, = get_args(annotation_type) | ||
| elif annotation_origin is NotRequired: | ||
| yield NotRequired | ||
| annotation_type, = get_args(annotation_type) | ||
| elif annotation_origin is ReadOnly: | ||
| yield ReadOnly | ||
| annotation_type, = get_args(annotation_type) | ||
| else: | ||
| break | ||
| class _TypedDictMeta(type): | ||
| def __new__(cls, name, bases, ns, total=True): | ||
| def __new__(cls, name, bases, ns, *, total=True): | ||
| """Create new typed dict class object. | ||
| This method is called when TypedDict is subclassed, | ||
| @@ -830,33 +853,46 @@ def __new__(cls, name, bases, ns, total=True): | ||
| } | ||
| required_keys = set() | ||
| optional_keys = set() | ||
| readonly_keys = set() | ||
| mutable_keys = set() | ||
| for base in bases: | ||
| annotations.update(base.__dict__.get('__annotations__', {})) | ||
| required_keys.update(base.__dict__.get('__required_keys__', ())) | ||
| optional_keys.update(base.__dict__.get('__optional_keys__', ())) | ||
| base_dict = base.__dict__ | ||
| annotations.update(base_dict.get('__annotations__', {})) | ||
| required_keys.update(base_dict.get('__required_keys__', ())) | ||
| optional_keys.update(base_dict.get('__optional_keys__', ())) | ||
| readonly_keys.update(base_dict.get('__readonly_keys__', ())) | ||
| mutable_keys.update(base_dict.get('__mutable_keys__', ())) | ||
| annotations.update(own_annotations) | ||
| for annotation_key, annotation_type in own_annotations.items(): | ||
| annotation_origin = get_origin(annotation_type) | ||
| if annotation_origin is Annotated: | ||
| annotation_args = get_args(annotation_type) | ||
| if annotation_args: | ||
| annotation_type = annotation_args[0] | ||
| annotation_origin = get_origin(annotation_type) | ||
| if annotation_origin is Required: | ||
| qualifiers = set(_get_typeddict_qualifiers(annotation_type)) | ||
| if Required in qualifiers: | ||
| required_keys.add(annotation_key) | ||
| elif annotation_origin is NotRequired: | ||
| elif NotRequired in qualifiers: | ||
| optional_keys.add(annotation_key) | ||
| elif total: | ||
| required_keys.add(annotation_key) | ||
| else: | ||
| optional_keys.add(annotation_key) | ||
| if ReadOnly in qualifiers: | ||
| if annotation_key in mutable_keys: | ||
| raise TypeError( | ||
| f"Cannot override mutable key {annotation_key!r}" | ||
| " with read-only key" | ||
| ) | ||
| readonly_keys.add(annotation_key) | ||
| else: | ||
| mutable_keys.add(annotation_key) | ||
| readonly_keys.discard(annotation_key) | ||
| tp_dict.__annotations__ = annotations | ||
| tp_dict.__required_keys__ = frozenset(required_keys) | ||
| tp_dict.__optional_keys__ = frozenset(optional_keys) | ||
| tp_dict.__readonly_keys__ = frozenset(readonly_keys) | ||
| tp_dict.__mutable_keys__ = frozenset(mutable_keys) | ||
| if not hasattr(tp_dict, '__total__'): | ||
| tp_dict.__total__ = total | ||
| return tp_dict | ||
| @@ -937,6 +973,8 @@ class Point2D(TypedDict): | ||
| raise TypeError("TypedDict takes either a dict or keyword arguments," | ||
| " but not both") | ||
| if kwargs: | ||
| if sys.version_info >= (3, 13): | ||
| raise TypeError("TypedDict takes no keyword arguments") | ||
| warnings.warn( | ||
| "The kwargs-based syntax for TypedDict definitions is deprecated " | ||
| "in Python 3.11, will be removed in Python 3.13, and may not be " | ||
| @@ -1925,6 +1963,53 @@ class Movie(TypedDict): | ||
| """) | ||
| if hasattr(typing, 'ReadOnly'): | ||
| ReadOnly = typing.ReadOnly | ||
| elif sys.version_info[:2] >= (3, 9): # 3.9-3.12 | ||
| @_ExtensionsSpecialForm | ||
| def ReadOnly(self, parameters): | ||
| """A special typing construct to mark an item of a TypedDict as read-only. | ||
| For example: | ||
JelleZijlstra marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| class Movie(TypedDict): | ||
| title: ReadOnly[str] | ||
| year: int | ||
| def mutate_movie(m: Movie) -> None: | ||
| m["year"] = 1992 # allowed | ||
| m["title"] = "The Matrix" # typechecker error | ||
| There is no runtime checking for this property. | ||
| """ | ||
| item = typing._type_check(parameters, f'{self._name} accepts only a single type.') | ||
| return typing._GenericAlias(self, (item,)) | ||
| else: # 3.8 | ||
| class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True): | ||
| def __getitem__(self, parameters): | ||
| item = typing._type_check(parameters, | ||
| f'{self._name} accepts only a single type.') | ||
| return typing._GenericAlias(self, (item,)) | ||
| ReadOnly = _ReadOnlyForm( | ||
| 'ReadOnly', | ||
| doc="""A special typing construct to mark a key of a TypedDict as read-only. | ||
| For example: | ||
JelleZijlstra marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| class Movie(TypedDict): | ||
| title: ReadOnly[str] | ||
| year: int | ||
| def mutate_movie(m: Movie) -> None: | ||
| m["year"] = 1992 # allowed | ||
| m["title"] = "The Matrix" # typechecker error | ||
| There is no runtime checking for this propery. | ||
| """) | ||
| _UNPACK_DOC = """\ | ||
| Type unpack operator. | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.