8000 gh-92114: Improve error message for types with __class_getitem__ = None by serhiy-storchaka · Pull Request #92115 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-92114: Improve error message for types with __class_getitem__ = None #92115

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
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
gh-92114: Improve error message for types with __class_getitem__ = None
  • Loading branch information
serhiy-storchaka committed May 1, 2022
commit 1dabc3a3a141dc3c03ba70bc6b0038cc9e04d6d6
8 changes: 8 additions & 0 deletions Lib/test/test_genericclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ def __class_getitem__(cls):
return None
with self.assertRaises(TypeError):
C_too_few[int]

class C_too_many:
def __class_getitem__(cls, one, two):
return None
Expand All @@ -232,16 +233,23 @@ def __class_getitem__(cls, item):
return None
with self.assertRaises(TypeError):
C()[int]

class E: ...
e = E()
e.__class_getitem__ = lambda cls, item: 'This will not work'
with self.assertRaises(TypeError):
e[int]

class C_not_callable:
__class_getitem__ = "Surprise!"
with self.assertRaises(TypeError):
C_not_callable[int]

class C_is_none(tuple):
__class_getitem__ = None
with self.assertRaisesRegex(TypeError, "C_is_none"):
C_is_none[int]

def test_class_getitem_metaclass(self):
class Meta(type):
def __class_getitem__(cls, item):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve error message when subscript a type with ``__class_getitem__`` set
to ``None``.
3 changes: 2 additions & 1 deletion Objects/abstract.c
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,12 @@ PyObject_GetItem(PyObject *o, PyObject *key)
if (_PyObject_LookupAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
return NULL;
}
if (meth) {
if (meth && meth != Py_None) {
result = PyObject_CallOneArg(meth, key);
Py_DECREF(meth);
return result;
}
Py_XDECREF(meth);
PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
((PyTypeObject *)o)->tp_name);
return NULL;
Expand Down
0