test_kwargs_and_defaults.cpp revision 12391:ceeca8b41e4b
1/*
2    tests/test_kwargs_and_defaults.cpp -- keyword arguments and default values
3
4    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6    All rights reserved. Use of this source code is governed by a
7    BSD-style license that can be found in the LICENSE file.
8*/
9
10#include "pybind11_tests.h"
11#include <pybind11/stl.h>
12
13TEST_SUBMODULE(kwargs_and_defaults, m) {
14    auto kw_func = [](int x, int y) { return "x=" + std::to_string(x) + ", y=" + std::to_string(y); };
15
16    // test_named_arguments
17    m.def("kw_func0", kw_func);
18    m.def("kw_func1", kw_func, py::arg("x"), py::arg("y"));
19    m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200);
20    m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!"));
21
22    /* A fancier default argument */
23    std::vector<int> list{{13, 17}};
24    m.def("kw_func4", [](const std::vector<int> &entries) {
25        std::string ret = "{";
26        for (int i : entries)
27            ret += std::to_string(i) + " ";
28        ret.back() = '}';
29        return ret;
30    }, py::arg("myList") = list);
31
32    m.def("kw_func_udl", kw_func, "x"_a, "y"_a=300);
33    m.def("kw_func_udl_z", kw_func, "x"_a, "y"_a=0);
34
35    // test_args_and_kwargs
36    m.def("args_function", [](py::args args) -> py::tuple { return args; });
37    m.def("args_kwargs_function", [](py::args args, py::kwargs kwargs) {
38        return py::make_tuple(args, kwargs);
39    });
40
41    // test_mixed_args_and_kwargs
42    m.def("mixed_plus_args", [](int i, double j, py::args args) {
43        return py::make_tuple(i, j, args);
44    });
45    m.def("mixed_plus_kwargs", [](int i, double j, py::kwargs kwargs) {
46        return py::make_tuple(i, j, kwargs);
47    });
48    auto mixed_plus_both = [](int i, double j, py::args args, py::kwargs kwargs) {
49        return py::make_tuple(i, j, args, kwargs);
50    };
51    m.def("mixed_plus_args_kwargs", mixed_plus_both);
52
53    m.def("mixed_plus_args_kwargs_defaults", mixed_plus_both,
54            py::arg("i") = 1, py::arg("j") = 3.14159);
55
56    // pybind11 won't allow these to be bound: args and kwargs, if present, must be at the end.
57    // Uncomment these to test that the static_assert is indeed working:
58//    m.def("bad_args1", [](py::args, int) {});
59//    m.def("bad_args2", [](py::kwargs, int) {});
60//    m.def("bad_args3", [](py::kwargs, py::args) {});
61//    m.def("bad_args4", [](py::args, int, py::kwargs) {});
62//    m.def("bad_args5", [](py::args, py::kwargs, int) {});
63//    m.def("bad_args6", [](py::args, py::args) {});
64//    m.def("bad_args7", [](py::kwargs, py::kwargs) {});
65
66    // test_function_signatures (along with most of the above)
67    struct KWClass { void foo(int, float) {} };
68    py::class_<KWClass>(m, "KWClass")
69        .def("foo0", &KWClass::foo)
70        .def("foo1", &KWClass::foo, "x"_a, "y"_a);
71}
72