]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-128335: Make slice generic at runtime (#128336)
authorJames Hilton-Balfe <gobot1234yt@gmail.com>
Sun, 11 Jan 2026 19:27:24 +0000 (19:27 +0000)
committerGitHub <noreply@github.com>
Sun, 11 Jan 2026 19:27:24 +0000 (11:27 -0800)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Doc/reference/datamodel.rst
Doc/whatsnew/3.15.rst
Lib/test/test_genericalias.py
Misc/NEWS.d/next/Core_and_Builtins/2024-12-29-21-33-08.gh-issue-128334.3c5Nou.rst [new file with mode: 0644]
Objects/sliceobject.c

index 488fbc6b1f68cd3d5c9d112d8b0f7122b61cb8c3..1bfe6b7375bcf7ecdb9dfddda86fe35faf270b81 100644 (file)
@@ -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 <subscriptions>`. 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)
index 115b7b3c86e03467fb1a720347ca21e4ff52e13d..a4eeb568dae433890911324ba3fa27be64932715 100644 (file)
@@ -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
 ===========
index 9df9296e26ad5c9147cf6fb8a295e49926342ef5..0017c093166dd285886806670d9a5f7bfaddd3df 100644 (file)
@@ -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 (file)
index 0000000..2908db8
--- /dev/null
@@ -0,0 +1 @@
+Make the :class:`slice` class subscriptable at runtime to be consistent with typing implementation.
index 5186ff4f6f0cf5f7a2d0594ce4c2ee5ba0926be6..2a402bb3347d603d9ad7829dfbed631ea364e863 100644 (file)
@@ -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}
 };