Skip to content

fix: provide useful behavior of default py::slice #5620

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 3 commits into from
Apr 16, 2025
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
3 changes: 2 additions & 1 deletion include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -1942,13 +1942,14 @@ class weakref : public object {

class slice : public object {
public:
PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
PYBIND11_OBJECT(slice, object, PySlice_Check)
slice(handle start, handle stop, handle step)
: object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {
if (!m_ptr) {
pybind11_fail("Could not allocate slice object!");
}
}
slice() : slice(none(), none(), none()) {}

#ifdef PYBIND11_HAS_OPTIONAL
slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
Expand Down
2 changes: 2 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,8 @@ TEST_SUBMODULE(pytypes, m) {

m.def("test_list_slicing", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });

m.def("test_list_slicing_default", [](const py::list &a) { return a[py::slice()]; });

// See #2361
m.def("issue2361_str_implicit_copy_none", []() {
py::str is_this_none = py::none();
Expand Down
3 changes: 2 additions & 1 deletion tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,8 @@ def test_number_protocol():

def test_list_slicing():
li = list(range(100))
assert li[::2] == m.test_list_slicing(li)
assert li[0:-1:2] == m.test_list_slicing(li)
assert li[::] == m.test_list_slicing_default(li)


def test_issue2361():
Expand Down
Loading