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.

62 lines
1.9 KiB

  1. /*
  2. example/example11.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 "example.h"
  8. #include <pybind11/stl.h>
  9. void kw_func(int x, int y) { std::cout << "kw_func(x=" << x << ", y=" << y << ")" << std::endl; }
  10. void kw_func4(const std::vector<int> &entries) {
  11. std::cout << "kw_func4: ";
  12. for (int i : entries)
  13. std::cout << i << " ";
  14. std::cout << endl;
  15. }
  16. py::object call_kw_func(py::function f) {
  17. py::tuple args = py::make_tuple(1234);
  18. py::dict kwargs;
  19. kwargs["y"] = py::cast(5678);
  20. return f(*args, **kwargs);
  21. }
  22. void args_function(py::args args) {
  23. for (size_t it=0; it<args.size(); ++it)
  24. std::cout << "got argument: " << py::object(args[it]) << std::endl;
  25. }
  26. void args_kwargs_function(py::args args, py::kwargs kwargs) {
  27. for (auto item : args)
  28. std::cout << "got argument: " << item << std::endl;
  29. if (kwargs) {
  30. for (auto item : kwargs)
  31. std::cout << "got keyword argument: " << item.first << " -> " << item.second << std::endl;
  32. }
  33. }
  34. void init_ex11(py::module &m) {
  35. m.def("kw_func", &kw_func, py::arg("x"), py::arg("y"));
  36. m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200);
  37. m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!"));
  38. /* A fancier default argument */
  39. std::vector<int> list;
  40. list.push_back(13);
  41. list.push_back(17);
  42. m.def("kw_func4", &kw_func4, py::arg("myList") = list);
  43. m.def("call_kw_func", &call_kw_func);
  44. m.def("args_function", &args_function);
  45. m.def("args_kwargs_function", &args_kwargs_function);
  46. using namespace py::literals;
  47. m.def("kw_func_udl", &kw_func, "x"_a, "y"_a=300);
  48. m.def("kw_func_udl_z", &kw_func, "x"_a, "y"_a=0);
  49. }