From: James Hilton-Balfe Date: Sun, 11 Jan 2026 19:27:24 +0000 (+0000) Subject: gh-128335: Make slice generic at runtime (#128336) X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=265381b7e8bba00fefb40339d55fbe88133d4c04;p=thirdparty%2FPython%2Fcpython.git gh-128335: Make slice generic at runtime (#128336) Co-authored-by: Jelle Zijlstra --- diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 488fbc6b1f68..1bfe6b7375bc 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1819,6 +1819,12 @@ Slice objects are used to represent slices for :meth:`~object.__getitem__` methods. They are also created by the built-in :func:`slice` function. +.. versionadded:: 3.15 + + The :func:`slice` type now supports :ref:`subscription `. For + example, ``slice[float]`` may be used in type annotations to indicate a slice + containing :type:`float` objects. + .. index:: single: start (slice object attribute) single: stop (slice object attribute) diff --git a/Doc/whatsnew/3.15.rst b/Doc/whatsnew/3.15.rst index 115b7b3c86e0..a4eeb568dae4 100644 --- a/Doc/whatsnew/3.15.rst +++ b/Doc/whatsnew/3.15.rst @@ -402,6 +402,9 @@ Other language changes :class:`tuple` (including classes created by :func:`collections.namedtuple`). (Contributed by Serhiy Storchaka in :gh:`41779`.) +* The :class:`slice` type now supports subscription, + making it a :term:`generic type`. + (Contributed by James Hilton-Balfe in :gh:`128335`.) New modules =========== diff --git a/Lib/test/test_genericalias.py b/Lib/test/test_genericalias.py index 9df9296e26ad..0017c093166d 100644 --- a/Lib/test/test_genericalias.py +++ b/Lib/test/test_genericalias.py @@ -102,6 +102,7 @@ _UNPACKED_TUPLES = [ class BaseTest(unittest.TestCase): """Test basics.""" generic_types = [type, tuple, list, dict, set, frozenset, enumerate, memoryview, + slice, defaultdict, deque, SequenceMatcher, dircmp, diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-12-29-21-33-08.gh-issue-128334.3c5Nou.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-29-21-33-08.gh-issue-128334.3c5Nou.rst new file mode 100644 index 000000000000..2908db863e07 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-29-21-33-08.gh-issue-128334.3c5Nou.rst @@ -0,0 +1 @@ +Make the :class:`slice` class subscriptable at runtime to be consistent with typing implementation. diff --git a/Objects/sliceobject.c b/Objects/sliceobject.c index 5186ff4f6f0c..2a402bb3347d 100644 --- a/Objects/sliceobject.c +++ b/Objects/sliceobject.c @@ -569,6 +569,7 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef slice_methods[] = { {"indices", slice_indices, METH_O, slice_indices_doc}, {"__reduce__", slice_reduce, METH_NOARGS, reduce_doc}, + {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}, {NULL, NULL} };