8000 bpo-42195: Ensure consistency of Callable's __args__ in collections.abc and typing by Fidget-Spinner · Pull Request #23060 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

bpo-42195: Ensure consistency of Callable's __args__ in collections.abc and typing #23060

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 31 commits into from
Dec 13, 2020
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
8000 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
Next Next commit
Allow subclassing of GenericAlias, fix collections.abc.Callable's Gen…
…ericAlias
  • Loading branch information
Fidget-Spinner committed Nov 19, 2020
commit 2c4a297703423a8ffc9680cc633c86ccfaae47b1
62 changes: 61 additions & 1 deletion Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from abc import ABCMeta, abstractmethod
import sys
import types

GenericAlias = type(list[int])

Expand Down Expand Up @@ -409,6 +410,65 @@ def __subclasshook__(cls, C):
return NotImplemented


class _CallableGenericAlias(GenericAlias):
""" Internal class specifically for consistency between the ``__args__`` of
``collections.abc.Callable``'s and ``typing.Callable``'s ``GenericAlias``.

See :issue:`42195`.
"""
def __new__(cls, *args, **kwargs):
if not isinstance(args, tuple) or len(args) != 2:
raise TypeError("Callable must be used as "
"Callable[[arg, ...], result].")
_typ, _args = 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 not isinstance(t_args, list):
raise TypeError("Callable must be used as "
"Callable[[arg, ...], result].")

ga_args = []
for arg in args[1]:
if isinstance(arg, list):
ga_args.extend(arg)
else:
ga_args.append(arg)
return super().__new__(cls, _typ, tuple(ga_args))

def __init__(self, *args, **kwargs):
pass

def __repr__(self):
t_args = self.__args__[:-1]
t_result = self.__args__[-1]
return f"{_type_repr(self.__origin__)}" \
f"[[{', '.join(_type_repr(a) for a in t_args)}], " \
f"{_type_repr(t_result)}]"


def _type_repr(obj):
"""Return the repr() of an object, special-casing types (internal helper).

If obj is a type, we return a shorter version than the default
type.__repr__, based on the module and qualified name, which is
typically enough to uniquely identify a type. For everything
else, we fall back on repr(obj).

Borrowed from :mod:`typing`.
"""
if isinstance(obj, type):
if obj.__module__ == 'builtins':
return obj.__qualname__
return f'{obj.__module__}.{obj.__qualname__}'
if obj is ...:
return('...')
if isinstance(obj, types.FunctionType):
return obj.__name__
return repr(obj)


class Callable(metaclass=ABCMeta):

__slots__ = ()
Expand All @@ -423,7 +483,7 @@ def __subclasshook__(cls, C):
return _check_methods(C, "__call__")
return NotImplemented

__class_getitem__ = classmethod(GenericAlias)
__class_getitem__ = classmethod(_CallableGenericAlias)


### SETS ###
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_genericalias.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,25 @@ def test_weakref(self):
alias = t[int]
self.assertEqual(ref(alias)(), alias)

def test_abc_callable(self):
alias = Callable[[int, str], float]
with self.subTest("Testing collections.abc.Callable's subscription"):
self.assertIs(alias.__origin__, Callable)
self.assertEqual(alias.__args__, (int, str, float))
self.assertEqual(alias.__parameters__, ())

with self.subTest("Testing collections.abc.Callable's instance checks"):
self.assertIsInstance(alias, GenericAlias)

invalid_params = ('Callable[int]', 'Callable[int, str]')
with self.subTest("Testing collections.abc.Callable's parameter "
"validation"):
for bad in invalid_params:
with self.subTest(f'Testing expression {bad}'):
with self.assertRaises(TypeError):
eval(bad)



if __name__ == "__main__":
unittest.main()
29 changes: 26 additions & 3 deletions Objects/genericaliasobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -567,15 +567,38 @@ static PyGetSetDef ga_properties[] = {
static PyObject *
ga_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
gaobject *self;

assert(type != NULL && type->tp_alloc != NULL);
self = (gaobject *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;

if (!_PyArg_NoKwnames("GenericAlias", kwds)) {
return NULL;
}
if (!_PyArg_CheckPositional("GenericAlias", PyTuple_GET_SIZE(args), 2, 2)) {
return NULL;
}
PyObject *origin = PyTuple_GET_ITEM(args, 0);
PyObject *origin = PyTuple_GET_ITEM(args, 0);
PyObject *arguments = PyTuple_GET_ITEM(args, 1);
return Py_GenericAlias(origin, arguments);

// almost the same as Py_GenericAlias' code, but to assign to self
Copy link
Member

Choose a reason for hiding this comment

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

I'd refactor this to avoid so much code duplication. Also, I'm sorry, I have forgotten this detail myself, I wonder what the difference is between what tp_alloc calls (PyType_GenericAlloc) and what Py_GenericAlias calls (PyObject_GC_New).

Copy link
Member Author

Choose a reason for hiding this comment

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

Same here, from what I can see PyType_GenericAlloc calls _PyObject_GC_Malloc if Py_TPFLAGS_HAVE_GC flag is set, else it will call PyObject_MALLOC. While PyObject_GC_New calls _PyObject_GC_Malloc all the time. So it should be okay to replace one with another since that flag is set.

Copy link
Member
@pablogsal < 9E19 strong> pablogsal Dec 13, 2020

Choose a reason for hiding this comment

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

Normally when calling tp_alloc directly instead of PyObject_GC_New is to allow subclasses to override the allocators, although using tp_alloc can be anecdotally slower.

if (!PyTuple_Check(arguments)) {
arguments = PyTuple_Pack(1, arguments);
if (arguments == NULL) {
return NULL;
}
}
else {
Py_INCREF(arguments);
}

Py_INCREF(origin);
self->origin = origin;
self->args = arguments;
self->parameters = NULL;
return (PyObject *) self;
}

static PyNumberMethods ga_as_number = {
Expand All @@ -600,7 +623,7 @@ PyTypeObject Py_GenericAliasType = {
.tp_hash = ga_hash,
.tp_call = ga_call,
.tp_getattro = ga_getattro,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
.tp_traverse = ga_traverse,
.tp_richcompare = ga_richcompare,
.tp_weaklistoffset = offsetof(gaobject, weakreflist),
Expand Down
0