Skip to content

Commit 265381b

Browse files
gh-128335: Make slice generic at runtime (#128336)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 620a5b9 commit 265381b

File tree

5 files changed

+12
-0
lines changed

5 files changed

+12
-0
lines changed

Doc/reference/datamodel.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1819,6 +1819,12 @@ Slice objects are used to represent slices for
18191819
:meth:`~object.__getitem__`
18201820
methods. They are also created by the built-in :func:`slice` function.
18211821

1822+
.. versionadded:: 3.15
1823+
1824+
The :func:`slice` type now supports :ref:`subscription <subscriptions>`. For
1825+
example, ``slice[float]`` may be used in type annotations to indicate a slice
1826+
containing :type:`float` objects.
1827+
18221828
.. index::
18231829
single: start (slice object attribute)
18241830
single: stop (slice object attribute)

Doc/whatsnew/3.15.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,9 @@ Other language changes
402402
:class:`tuple` (including classes created by :func:`collections.namedtuple`).
403403
(Contributed by Serhiy Storchaka in :gh:`41779`.)
404404

405+
* The :class:`slice` type now supports subscription,
406+
making it a :term:`generic type`.
407+
(Contributed by James Hilton-Balfe in :gh:`128335`.)
405408

406409
New modules
407410
===========

Lib/test/test_genericalias.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@
102102
class BaseTest(unittest.TestCase):
103103
"""Test basics."""
104104
generic_types = [type, tuple, list, dict, set, frozenset, enumerate, memoryview,
105+
slice,
105106
defaultdict, deque,
106107
SequenceMatcher,
107108
dircmp,
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make the :class:`slice` class subscriptable at runtime to be consistent with typing implementation.

Objects/sliceobject.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,7 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
569569
static PyMethodDef slice_methods[] = {
570570
{"indices", slice_indices, METH_O, slice_indices_doc},
571571
{"__reduce__", slice_reduce, METH_NOARGS, reduce_doc},
572+
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"},
572573
{NULL, NULL}
573574
};
574575

0 commit comments

Comments
 (0)