You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.6 KiB

  1. /*
  2. tests/test_kwargs_and_defaults.cpp -- keyword arguments and default values
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. #include <pybind11/stl.h>
  9. std::string kw_func(int x, int y) { return "x=" + std::to_string(x) + ", y=" + std::to_string(y); }
  10. std::string kw_func4(const std::vector<int> &entries) {
  11. std::string ret = "{";
  12. for (int i : entries)
  13. ret += std::to_string(i) + " ";
  14. ret.back() = '}';
  15. return ret;
  16. }
  17. py::tuple args_function(py::args args) {
  18. return args;
  19. }
  20. py::tuple args_kwargs_function(py::args args, py::kwargs kwargs) {
  21. return py::make_tuple(args, kwargs);
  22. }
  23. struct KWClass {
  24. void foo(int, float) {}
  25. };
  26. test_initializer arg_keywords_and_defaults([](py::module &m) {
  27. m.def("kw_func0", &kw_func);
  28. m.def("kw_func1", &kw_func, py::arg("x"), py::arg("y"));
  29. m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200);
  30. m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!"));
  31. /* A fancier default argument */
  32. std::vector<int> list;
  33. list.push_back(13);
  34. list.push_back(17);
  35. m.def("kw_func4", &kw_func4, py::arg("myList") = list);
  36. m.def("args_function", &args_function);
  37. m.def("args_kwargs_function", &args_kwargs_function);
  38. m.def("kw_func_udl", &kw_func, "x"_a, "y"_a=300);
  39. m.def("kw_func_udl_z", &kw_func, "x"_a, "y"_a=0);
  40. py::class_<KWClass>(m, "KWClass")
  41. .def("foo0", &KWClass::foo)
  42. .def("foo1", &KWClass::foo, "x"_a, "y"_a);
  43. });