feat: Slice allowing None with py::object or std::optional (#1101)

* Adding nullptr slices

Using example from #1095

Some fixes from @wjakob's review

Stop clang-tidy from complaining

New proposal for py::slice constructor

Eric's suggested changes: simplify testing; shift def's

* chore: drop MSVC pragma (hopefully unneeded)

* Apply suggestions from code review
This commit is contained in:
Henry Schreiner
2021-09-22 17:41:56 -04:00
committed by GitHub
parent 0fb981b219
commit b06a6f4f62
5 changed files with 78 additions and 24 deletions

View File

@@ -17,6 +17,11 @@
#include <utility>
#include <vector>
#ifdef PYBIND11_HAS_OPTIONAL
#include <optional>
#endif // PYBIND11_HAS_OPTIONAL
template<typename T>
class NonZeroIterator {
const T* ptr_;
@@ -117,6 +122,18 @@ TEST_SUBMODULE(sequences_and_iterators, m) {
return std::make_tuple(istart, istop, istep);
});
m.def("make_forward_slice_size_t", []() { return py::slice(0, -1, 1); });
m.def("make_reversed_slice_object", []() { return py::slice(py::none(), py::none(), py::int_(-1)); });
#ifdef PYBIND11_HAS_OPTIONAL
m.attr("has_optional") = true;
m.def("make_reversed_slice_size_t_optional_verbose", []() { return py::slice(std::nullopt, std::nullopt, -1); });
// Warning: The following spelling may still compile if optional<> is not present and give wrong answers.
// Please use with caution.
m.def("make_reversed_slice_size_t_optional", []() { return py::slice({}, {}, -1); });
#else
m.attr("has_optional") = false;
#endif
// test_sequence
class Sequence {
public: