Implement support for PEP 764 (inline typed dictionaries)#580
Merged
AlexWaygood merged 7 commits intopython:mainfrom Apr 25, 2025
Merged
Implement support for PEP 764 (inline typed dictionaries)#580AlexWaygood merged 7 commits intopython:mainfrom
AlexWaygood merged 7 commits intopython:mainfrom
Conversation
This was referenced Apr 7, 2025
AlexWaygood
reviewed
Apr 19, 2025
Member
|
I would be tempted to move the complexity out of Currently on this PR we get the following: >>> from typing_extensions import TypedDict
>>> import inspect
>>> inspect.signature(TypedDict)
<Signature (typename, fields=<sentinel>, /, *, total=True, closed=None, extra_items=typing_extensions.NoExtraItems, __typing_is_inline__=False, **kwargs)>but if you made this change: Suggested patchdiff --git a/src/typing_extensions.py b/src/typing_extensions.py
index 9c727a8..dfbaa7d 100644
--- a/src/typing_extensions.py
+++ b/src/typing_extensions.py
@@ -1079,6 +1079,68 @@ else:
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
+ def _create_typeddict(
+ typename,
+ fields,
+ /,
+ *,
+ typing_is_inline,
+ total,
+ closed,
+ extra_items,
+ **kwargs
+ ):
+ if fields is _marker or fields is None:
+ if fields is _marker:
+ deprecated_thing = (
+ "Failing to pass a value for the 'fields' parameter"
+ )
+ else:
+ deprecated_thing = "Passing `None` as the 'fields' parameter"
+
+ example = f"`{typename} = TypedDict({typename!r}, {{}})`"
+ deprecation_msg = (
+ f"{deprecated_thing} is deprecated and will be disallowed in "
+ "Python 3.15. To create a TypedDict class with 0 fields "
+ "using the functional syntax, pass an empty dictionary, e.g. "
+ ) + example + "."
+ warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
+ # Support a field called "closed"
+ if closed is not False and closed is not True and closed is not None:
+ kwargs["closed"] = closed
+ closed = None
+ # Or "extra_items"
+ if extra_items is not NoExtraItems:
+ kwargs["extra_items"] = extra_items
+ extra_items = NoExtraItems
+ fields = kwargs
+ elif kwargs:
+ 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 "
+ "understood by third-party type checkers.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ ns = {'__annotations__': dict(fields)}
+ module = _caller(depth=5 if typing_is_inline else 3)
+ if module is not None:
+ # Setting correct module is necessary to make typed dict classes
+ # pickleable.
+ ns['__module__'] = module
+
+ td = _TypedDictMeta(typename, (), ns, total=total, closed=closed,
+ extra_items=extra_items)
+ td.__orig_bases__ = (TypedDict,)
+ return td
+
+
class _TypedDictSpecialForm(_ExtensionsSpecialForm, _root=True):
def __call__(
self,
@@ -1089,60 +1151,22 @@ else:
total=True,
closed=None,
extra_items=NoExtraItems,
- __typing_is_inline__=False,
**kwargs
):
- if fields is _marker or fields is None:
- if fields is _marker:
- deprecated_thing = (
- "Failing to pass a value for the 'fields' parameter"
- )
- else:
- deprecated_thing = "Passing `None` as the 'fields' parameter"
-
- example = f"`{typename} = TypedDict({typename!r}, {{}})`"
- deprecation_msg = (
- f"{deprecated_thing} is deprecated and will be disallowed in "
- "Python 3.15. To create a TypedDict class with 0 fields "
- "using the functional syntax, pass an empty dictionary, e.g. "
- ) + example + "."
- warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
- # Support a field called "closed"
- if closed is not False and closed is not True and closed is not None:
- kwargs["closed"] = closed
- closed = None
- # Or "extra_items"
- if extra_items is not NoExtraItems:
- kwargs["extra_items"] = extra_items
- extra_items = NoExtraItems
- fields = kwargs
- elif kwargs:
- 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 "
- "understood by third-party type checkers.",
- DeprecationWarning,
- stacklevel=2,
- )
+ return _create_typeddict(
+ typename,
+ fields,
+ total=total,
+ closed=closed,
+ extra_items=extra_items,
+ typing_is_inline=False,
+ **kwargs
+ )
- ns = {'__annotations__': dict(fields)}
- module = _caller(depth=5 if __typing_is_inline__ else 2)
- if module is not None:
- # Setting correct module is necessary to make typed dict classes
- # pickleable.
- ns['__module__'] = module
+ def __mro_entries__(self, bases):
+ return (_TypedDict,)
- td = _TypedDictMeta(typename, (), ns, total=total, closed=closed,
- extra_items=extra_items)
- td.__orig_bases__ = (TypedDict,)
- return td
- @_ensure_subclassable(lambda bases: (_TypedDict,))
@_TypedDictSpecialForm
def TypedDict(self, args):
"""A simple typed namespace. At runtime it is equivalent to a plain dict.
@@ -1198,9 +1222,14 @@ else:
raise TypeError(
"TypedDict[...] should be used with a single dict argument"
)
-
- # Delegate to _TypedDictSpecialForm.__call__:
- return self("<inlined TypedDict>", args[0], __typing_is_inline__=True)
+ return _create_typeddict(
+ "<inlined TypedDict>",
+ args[0],
+ typing_is_inline=True,
+ total=True,
+ closed=None,
+ extra_items=NoExtraItems
+ )Then it would look like this: >>> from typing_extensions import TypedDict
>>> import inspect
>>> inspect.signature(TypedDict)
<Signature (typename, fields=<sentinel>, /, *, total=True, closed=None, extra_items=typing_extensions.NoExtraItems, **kwargs)>
>>> exit()(and all your tests still pass with that diff applied!) |
AlexWaygood
reviewed
Apr 23, 2025
Member
AlexWaygood
left a comment
There was a problem hiding this comment.
This looks great. A couple more minor comments:
AlexWaygood
approved these changes
Apr 25, 2025
Member
AlexWaygood
left a comment
There was a problem hiding this comment.
LGTM, thank you! Can you add an entry to CHANGELOG.md?
AlexWaygood
reviewed
Apr 25, 2025
JelleZijlstra
approved these changes
Apr 25, 2025
AlexWaygood
approved these changes
Apr 25, 2025
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
As suggested in #579 (comment).
Only downside is that the parent frame to be fetched is different depending on which syntax (functional or inline) is used. This means we need an extra argument (called
__typing_is_inline__in this PR) to differentiate the two. This isn't required in #579.There are also some issues on 3.8:
_ensure_subclassable()assumes it applies on functions on pypy for Python 3.8:typing_extensions/src/typing_extensions.py
Lines 866 to 878 in 281d7b0
which isn't the case here (the decorator is applied on the
_TypedDictSpecialForminstance).typing._SpecialFormis implemented quite differently on 3.8, so we would need to redefine__getitem__()on_TypedDictSpecialForm.Maybe support for 3.8 should be dropped first.done in #585.