| 15 | #include <utility> |
| 16 | |
| 17 | TEST_SUBMODULE(kwargs_and_defaults, m) { |
| 18 | auto kw_func |
| 19 | = [](int x, int y) { return "x=" + std::to_string(x) + ", y=" + std::to_string(y); }; |
| 20 | |
| 21 | // test_named_arguments |
| 22 | m.def("kw_func0", kw_func); |
| 23 | m.def("kw_func1", kw_func, py::arg("x"), py::arg("y")); |
| 24 | m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200); |
| 25 | m.def("kw_func3", [](const char *) {}, py::arg("data") = std::string("Hello world!")); |
| 26 | |
| 27 | /* A fancier default argument */ |
| 28 | std::vector<int> list{{13, 17}}; |
| 29 | m.def( |
| 30 | "kw_func4", |
| 31 | [](const std::vector<int> &entries) { |
| 32 | std::string ret = "{"; |
| 33 | for (int i : entries) { |
| 34 | ret += std::to_string(i) + " "; |
| 35 | } |
| 36 | ret.back() = '}'; |
| 37 | return ret; |
| 38 | }, |
| 39 | py::arg("myList") = list); |
| 40 | |
| 41 | m.def("kw_func_udl", kw_func, "x"_a, "y"_a = 300); |
| 42 | m.def("kw_func_udl_z", kw_func, "x"_a, "y"_a = 0); |
| 43 | |
| 44 | // test line breaks in default argument representation |
| 45 | struct CustomRepr { |
| 46 | std::string repr_string; |
| 47 | |
| 48 | explicit CustomRepr(const std::string &repr) : repr_string(repr) {} |
| 49 | |
| 50 | std::string __repr__() const { return repr_string; } |
| 51 | }; |
| 52 | |
| 53 | py::class_<CustomRepr>(m, "CustomRepr") |
| 54 | .def(py::init<const std::string &>()) |
| 55 | .def("__repr__", &CustomRepr::__repr__); |
| 56 | |
| 57 | m.def( |
| 58 | "kw_lb_func0", |
| 59 | [](const CustomRepr &) {}, |
| 60 | py::arg("custom") = CustomRepr(" array([[A, B], [C, D]]) ")); |
| 61 | m.def( |
| 62 | "kw_lb_func1", |
| 63 | [](const CustomRepr &) {}, |
| 64 | py::arg("custom") = CustomRepr(" array([[A, B],\n[C, D]]) ")); |
| 65 | m.def( |
| 66 | "kw_lb_func2", |
| 67 | [](const CustomRepr &) {}, |
| 68 | py::arg("custom") = CustomRepr("\v\n array([[A, B], [C, D]])")); |
| 69 | m.def( |
| 70 | "kw_lb_func3", |
| 71 | [](const CustomRepr &) {}, |
| 72 | py::arg("custom") = CustomRepr("array([[A, B], [C, D]]) \f\n")); |
| 73 | m.def( |
| 74 | "kw_lb_func4", |
nothing calls this directly
no test coverage detected