Skip to content
Closed
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
8 changes: 8 additions & 0 deletions Lib/test/test_genericalias.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,5 +293,13 @@ def test_dir(self):
for generic_alias_property in ("__origin__", "__args__", "__parameters__"):
self.assertIn(generic_alias_property, dir_of_gen_alias)

def test_indexing(self):
stmts = ['list[0]', 'list[0.0]', 'list[True]', 'list[1 + 3j]']
for stmt in stmts:
with self.subTest(stmt=stmt):
with self.assertRaises(TypeError):
eval(stmt)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Throw :exc:`TypeError` when attempting to index a generic type. For example,
``list[1]``.
6 changes: 6 additions & 0 deletions Objects/abstract.c
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,12 @@ PyObject_GetItem(PyObject *o, PyObject *key)
if ((PyTypeObject*)o == &PyType_Type) {
return Py_GenericAlias(o, key);
}
// To deny things like list[1], list[0.8], list[True], list[3 + 3j]
if (PyLong_CheckExact(key) || PyFloat_CheckExact(key)
|| PyBool_Check(key) || PyComplex_CheckExact(key)){
return type_error("generic type parameter must be a type, "
"not '%.200s'", key);
}

if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
return NULL;
Expand Down