-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
[3.9] bpo-42195: Ensure consistency of Callable's __args__ in collections.abc and typing (GH-23060) #23765
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
[3.9] bpo-42195: Ensure consistency of Callable's __args__ in collections.abc and typing (GH-23060) #23765
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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
Original file line number | Diff line number | Diff line change |
---|---|---|
8000
|
@@ -10,6 +10,10 @@ | |
import sys | ||
|
||
GenericAlias = type(list[int]) | ||
EllipsisType = type(...) | ||
def _f(): pass | ||
FunctionType = type(_f) | ||
del _f | ||
|
||
__all__ = ["Awaitable", "Coroutine", | ||
"AsyncIterable", "AsyncIterator", "AsyncGenerator", | ||
|
@@ -409,6 +413,76 @@ def __subclasshook__(cls, C): | |
return NotImplemented | ||
|
||
|
||
class _CallableGenericAlias(GenericAlias): | ||
""" Represent `Callable[argtypes, resulttype]`. | ||
|
||
This sets ``__args__`` to a tuple containing the flattened``argtypes`` | ||
followed by ``resulttype``. | ||
|
||
Example: ``Callable[[int, str], float]`` sets ``__args__`` to | ||
``(int, str, float)``. | ||
""" | ||
|
||
__slots__ = () | ||
|
||
def __new__(cls, origin, args): | ||
try: | ||
return cls.__create_ga(origin, args) | ||
except TypeError as exc: | ||
import warnings | ||
warnings.warn(f'{str(exc)} ' | ||
f'(This will raise a TypeError in Python 3.10.)', | ||
DeprecationWarning) | ||
return GenericAlias(origin, args) | ||
|
||
@classmethod | ||
def __create_ga(cls, origin, args): | ||
if not isinstance(args, tuple) or len(args) != 2: | ||
raise TypeError( | ||
"Callable must be used as Callable[[arg, ...], result].") | ||
t_args, t_result = args | ||
if isinstance(t_args, list): | ||
ga_args = tuple(t_args) + (t_result,) | ||
# This relaxes what t_args can be on purpose to allow things like | ||
# PEP 612 ParamSpec. Responsibility for whether a user is using | ||
# Callable[...] properly is deferred to static type checkers. | ||
else: | ||
ga_args = args | ||
return super().__new__(cls, origin, ga_args) | ||
|
||
def __repr__(self): | ||
if len(self.__args__) == 2 and self.__args__[0] is Ellipsis: | ||
return super().__repr__() | ||
return (f'collections.abc.Callable' | ||
f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], ' | ||
f'{_type_repr(self.__args__[-1])}]') | ||
|
||
def __reduce__(self): | ||
args = self.__args__ | ||
if not (len(args) == 2 and args[0] is Ellipsis): | ||
args = list(args[:-1]), args[-1] | ||
return _CallableGenericAlias, (Callable, args) | ||
|
||
|
||
def _type_repr(obj): | ||
"""Return the repr() of an object, special-casing types (internal helper). | ||
|
||
Copied from :mod:`typing` since collections.abc | ||
shouldn't depend on that module. | ||
""" | ||
if isinstance(obj, GenericAlias): | ||
return repr(obj) | ||
if isinstance(obj, type): | ||
if obj.__module__ == 'builtins': | ||
return obj.__qualname__ | ||
return f'{obj.__module__}.{obj.__qualname__}' | ||
if obj is Ellipsis: | ||
return '...' | ||
if isinstance(obj, FunctionType): | ||
return obj.__name__ | ||
return repr(obj) | ||
|
||
|
||
class Callable(metaclass=ABCMeta): | ||
|
||
__slots__ = () | ||
|
@@ -423,7 +497,7 @@ def __subclasshook__(cls, C): | |
return _check_methods(C, "__call__") | ||
return NotImplemented | ||
|
||
__class_getitem__ = classmethod(GenericAlias) | ||
__class_getitem__ = classmethod(_CallableGenericAlias) | ||
|
||
|
||
### SETS ### | ||
|
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 |
---|---|---|
@@ -1,2 +1,3 @@ | ||
from _collections_abc import * | ||
from _collections_abc import __all__ | ||
from _collections_abc import _CallableGenericAlias |
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
11 changes: 11 additions & 0 deletions
11
Misc/NEWS.d/next/Core and Builtins/2020-11-20-00-57-47.bpo-42195.HeqcpS.rst
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 |
---|---|---|
@@ -0,0 +1,11 @@ | ||
The ``__args__`` of the parameterized generics for :data:`typing.Callable` | ||
and :class:`collections.abc.Callable` are now consistent. The ``__args__`` | ||
for :class:`collections.abc.Callable` are now flattened while | ||
:data:`typing.Callable`'s have not changed. To allow this change, | ||
:class:`types.GenericAlias` can now be subclassed and | ||
``collections.abc.Callable``'s ``__class_getitem__`` will now return a subclass | ||
of ``types.GenericAlias``. Tests for typing were also updated to not subclass | ||
things like ``Callable[..., T]`` as that is not a valid base class. Finally, | ||
both ``Callable``s no longer validate their ``argtypes``, in | ||
``Callable[[argtypes], resulttype]`` to prepare for :pep:`612`. Patch by Ken Jin. | ||
|
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
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.