Skip to content

Implement support for PEP 764 (inline typed dictionaries) #580

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 7 commits into from
Apr 25, 2025

Conversation

Viicos
Copy link
Contributor

@Viicos Viicos commented Apr 7, 2025

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:

    def _ensure_subclassable(mro_entries):
    def inner(func):
    if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
    cls_dict = {
    "__call__": staticmethod(func),
    "__mro_entries__": staticmethod(mro_entries)
    }
    t = type(func.__name__, (), cls_dict)
    return functools.update_wrapper(t(), func)
    else:
    func.__mro_entries__ = mro_entries
    return func
    return inner

    which isn't the case here (the decorator is applied on the _TypedDictSpecialForm instance).

  • typing._SpecialForm is 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.

@AlexWaygood
Copy link
Member

I would be tempted to move the complexity out of _TypedDictSpecialForm.__call__ into a separate function. It means that you can keep the __typing_is_inline__ parameter out of _TypedDictSpecialForm.__call__, which means that it doesn't show up when users do inspect.signature(TypedDict).

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 patch
diff --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!)

@Viicos Viicos changed the title Implement support for PEP 764 (alternative implementation) Implement support for PEP 764 (inline typed dictionaries) Apr 23, 2025
Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

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

This looks great. A couple more minor comments:

Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

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

LGTM, thank you! Can you add an entry to CHANGELOG.md?

@AlexWaygood AlexWaygood merged commit 28f08ac into python:main Apr 25, 2025
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants