Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
2c4a297
Allow subclassing of GenericAlias, fix collections.abc.Callable's Gen…
Fidget-Spinner Oct 31, 2020
588d421
fix typing tests, add hash and eq methods
Fidget-Spinner Oct 31, 2020
050fa13
Fix pickling
Fidget-Spinner Oct 31, 2020
f60ea8a
whitespace
Fidget-Spinner Oct 31, 2020
2f3c6dc
Add test specifically for bpo
Fidget-Spinner Oct 31, 2020
2c4508e
update error message
Fidget-Spinner Oct 31, 2020
19d2973
Appease test_site
Fidget-Spinner Oct 31, 2020
3116c8e
Represent Callable __args__ via [tuple[args], result]
Fidget-Spinner Nov 19, 2020
f2b593a
add back tests for weakref, styling nits, add news
Fidget-Spinner Nov 19, 2020
93d51e4
remove redundant tuple checks leftover from old code
Fidget-Spinner Nov 19, 2020
327e1a5
Use _PosArgs instead of tuple
Fidget-Spinner Nov 28, 2020
e971ccb
Fix typo and news
Fidget-Spinner Nov 29, 2020
abd8b98
Refactor C code to use less duplication
Fidget-Spinner Nov 30, 2020
3ddca06
Address most of Guido's reviews (tests failing on purpose)
Fidget-Spinner Dec 1, 2020
1ab59c5
try to revert back to good old flat tuple __args__ days
Fidget-Spinner Dec 2, 2020
ee2d2e1
getting even closer
Fidget-Spinner Dec 2, 2020
2015738
finally done
Fidget-Spinner Dec 2, 2020
6704ffd
Update news
Fidget-Spinner Dec 4, 2020
598d29b
Address review partially
Fidget-Spinner Dec 5, 2020
c43ebcf
Address review fully, update news and tests, remove try-except block
Fidget-Spinner Dec 5, 2020
37ae3a9
Borrowed references don't need decref
Fidget-Spinner Dec 5, 2020
adbfcad
improve _PyArg_NoKwnames error handling, add union and subclass tests
Fidget-Spinner Dec 5, 2020
d1dd627
Don't change getargs, use _PyArg_NoKeywords instead
Fidget-Spinner Dec 5, 2020
2c21045
Merge remote-tracking branch 'upstream/master' into abc-callable-ga
Fidget-Spinner Dec 5, 2020
9f71667
remove stray whitespace
Fidget-Spinner Dec 5, 2020
a789620
refactor C code, add deprecation warning for 3.9
Fidget-Spinner Dec 6, 2020
1890b37
remove redundant check in C code, and try except in __new__
Fidget-Spinner Dec 6, 2020
4e928c6
remove check
Fidget-Spinner Dec 7, 2020
6b11d33
Loosen type checks for Callable args, cast to PyObject in genericalia…
Fidget-Spinner Dec 11, 2020
4215c3b
update news to mention about removing validation in argtypes
Fidget-Spinner Dec 11, 2020
585bf19
remove commented out code
Fidget-Spinner Dec 12, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Address review fully, update news and tests, remove try-except block
  • Loading branch information
Fidget-Spinner committed Dec 5, 2020
commit c43ebcf9cc51d62a2135934e6dca2920670aee3f
23 changes: 2 additions & 21 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,29 +422,10 @@ class _CallableGenericAlias(GenericAlias):
Example: ``Callable[[int, str], float]`` sets ``__args__`` to
``(int, str, float)``.
"""

__slots__ = ()
def __new__(cls, origin, args):
try:
return cls.__getitem_type(origin, args)
except TypeError:
# Fail-safe: most builtin generic collections don't validate the
# arguments passed to types.GenericAlias anyways.
# This is also because a subclass of the typing.Callable generic
# will have an __mro__ (<class 'MyCallable'>,
# <class 'collections.abc.Callable'>, <class 'typing.Generic'>,
# <class 'object'>). Subclasses wil use the __class_getitem__ of
# collections.abc.Callable before typing.Generic. As a result,
# we need to fall back on this to allow things like::
#
# T = TypeVar('T')
# class C1(typing.Callable[[T], T]): ...
# C1[int]
#
# Otherwise that will raise a TypeError.
return GenericAlias(origin, args)

@classmethod
def __getitem_type(cls, origin, args):
def __new__(cls, origin, args):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Okay, for 3.10 I think this is the right solution.

For 3.9, I think we need to issue a DeprecationWarning(using the warnings module) with the same message (for both TypeErrors below) and return what was returned in 3.9.0.

if not isinstance(args, tuple) or len(args) != 2:
raise TypeError(
"Callable must be used as Callable[[arg, ...], result]")
Expand Down
14 changes: 13 additions & 1 deletion Lib/test/test_genericalias.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,8 @@ def test_weakref(self):
self.assertEqual(ref(alias)(), alias)

def test_abc_callable(self):
Comment thread
Fidget-Spinner marked this conversation as resolved.
# A separate test is needed for Callable since it uses a subclass of
# GenericAlias.
alias = Callable[[int, str], float]
with self.subTest("Testing subscription"):
self.assertIs(alias.__origin__, Callable)
Expand All @@ -323,9 +325,19 @@ def test_abc_callable(self):

with self.subTest("Testing TypeVar substitution"):
C1 = Callable[[int, T], T]
self.assertEqual(C1[str], Callable[[int, str], str])
C2 = Callable[[K, T], V]
C3 = Callable[..., T]
self.assertEqual(C1[str], Callable[[int, str], str])
self.assertEqual(C2[int, float, str], Callable[[int, float], str])
self.assertEqual(C3[int], Callable[..., int])

with self.subTest("Testing type erasure"):
class C1(Callable):
def __call__(self):
return None
a = C1[[int], T]
self.assertIs(a().__class__, C1)
self.assertEqual(a().__orig_class__, C1[[int], T])

# bpo-42195
with self.subTest("Testing collections.abc.Callable's consistency "
Expand Down
23 changes: 11 additions & 12 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1802,10 +1802,9 @@ def barfoo2(x: CT): ...
def test_extended_generic_rules_subclassing(self):
class T1(Tuple[T, KT]): ...
class T2(Tuple[T, ...]): ...
class C1(Callable[[T], T]): ...
class C2(Callable[..., int]):
def __call__(self):
return None
class C1(typing.Container[T]):
def __contains__(self, item):
return False

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

So in the 3.9 backport this file should be untouched.


self.assertEqual(T1.__parameters__, (T, KT))
self.assertEqual(T1[int, str].__args__, (int, str))
Expand All @@ -1819,10 +1818,9 @@ def __call__(self):
## T2[int, str]

self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]')
self.assertEqual(C2.__parameters__, ())
self.assertIsInstance(C2(), collections.abc.Callable)
self.assertIsSubclass(C2, collections.abc.Callable)
self.assertIsSubclass(C1, collections.abc.Callable)
self.assertEqual(C1.__parameters__, (T,))
self.assertIsInstance(C1(), collections.abc.Container)
self.assertIsSubclass(C1, collections.abc.Container)
self.assertIsInstance(T1(), tuple)
self.assertIsSubclass(T2, tuple)
with self.assertRaises(TypeError):
Expand Down Expand Up @@ -1856,10 +1854,11 @@ def test_type_erasure_special(self):
class MyTup(Tuple[T, T]): ...
self.assertIs(MyTup[int]().__class__, MyTup)
self.assertEqual(MyTup[int]().__orig_class__, MyTup[int])
class MyCall(Callable[..., T]):
def __call__(self): return None
self.assertIs(MyCall[T]().__class__, MyCall)
self.assertEqual(MyCall[T]().__orig_class__, MyCall[T])
# This isn't valid as Callable isn't a valid base class.
## class MyCall(Callable[..., T]):
## def __call__(self): return None
## self.assertIs(MyCall[T]().__class__, MyCall)
## self.assertEqual(MyCall[T]().__orig_class__, MyCall[T])
Comment thread
Fidget-Spinner marked this conversation as resolved.
Outdated
class MyDict(typing.Dict[T, T]): ...
self.assertIs(MyDict[int]().__class__, MyDict)
self.assertEqual(MyDict[int]().__orig_class__, MyDict[int])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@ 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. Patch by Ken Jin.
: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. Patch by Ken Jin.