Skip to content
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

bpo-35992: Use PySequence_GetItem only if sq_item is not NULL #11857

Merged
merged 4 commits into from
Feb 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 8 additions & 1 deletion Lib/test/test_genericclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,14 @@ def __class_getitem__(cls, item):
return f'{cls.__name__}[{item.__name__}]'
self.assertEqual(Meta[int], 'Meta[int]')

def test_class_getitem_metaclass_2(self):
def test_class_getitem_with_metaclass(self):
class Meta(type): pass
class C(metaclass=Meta):
def __class_getitem__(cls, item):
return f'{cls.__name__}[{item.__name__}]'
self.assertEqual(C[int], 'C[int]')

def test_class_getitem_metaclass_first(self):
class Meta(type):
def __getitem__(cls, item):
return 'from metaclass'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix ``__class_getitem__()`` not being called on a class with a custom
non-subscriptable metaclass.
7 changes: 5 additions & 2 deletions Objects/abstract.c
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ PyObject *
PyObject_GetItem(PyObject *o, PyObject *key)
{
PyMappingMethods *m;
PySequenceMethods *ms;

if (o == NULL || key == NULL) {
return null_error();
Expand All @@ -155,17 +156,19 @@ PyObject_GetItem(PyObject *o, PyObject *key)
return item;
}

if (o->ob_type->tp_as_sequence) {
ms = o->ob_type->tp_as_sequence;
if (ms && ms->sq_item) {
if (PyIndex_Check(key)) {
Py_ssize_t key_value;
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (key_value == -1 && PyErr_Occurred())
return NULL;
return PySequence_GetItem(o, key_value);
}
else if (o->ob_type->tp_as_sequence->sq_item)
else {
return type_error("sequence index must "
"be integer, not '%.200s'", key);
}
}

if (PyType_Check(o)) {
Expand Down