-
-
Notifications
You must be signed in to change notification settings - Fork 118
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
Conversation
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!) |
There was a problem hiding this 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:
There was a problem hiding this 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
?
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
_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.