Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 1 | /* |
| 2 | example/example11.cpp -- keyword arguments and default values |
| 3 | |
Wenzel Jakob | 8cb6cb3 | 2016-04-17 20:21:41 +0200 | [diff] [blame] | 4 | Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 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 "example.h" |
Wenzel Jakob | 9180519 | 2016-01-17 22:36:43 +0100 | [diff] [blame] | 11 | #include <pybind11/stl.h> |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 12 | |
| 13 | void kw_func(int x, int y) { std::cout << "kw_func(x=" << x << ", y=" << y << ")" << std::endl; } |
| 14 | |
Wenzel Jakob | 9180519 | 2016-01-17 22:36:43 +0100 | [diff] [blame] | 15 | void kw_func4(const std::vector<int> &entries) { |
| 16 | std::cout << "kw_func4: "; |
| 17 | for (int i : entries) |
| 18 | std::cout << i << " "; |
| 19 | std::cout << endl; |
| 20 | } |
| 21 | |
Wenzel Jakob | 6c03beb | 2016-05-08 14:34:09 +0200 | [diff] [blame] | 22 | void call_kw_func(py::function f) { |
| 23 | py::tuple args = py::make_tuple(1234); |
| 24 | py::dict kwargs; |
| 25 | kwargs["y"] = py::cast(5678); |
| 26 | f(*args, **kwargs); |
| 27 | } |
| 28 | |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 29 | void init_ex11(py::module &m) { |
| 30 | m.def("kw_func", &kw_func, py::arg("x"), py::arg("y")); |
| 31 | m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200); |
Wenzel Jakob | 66c9a40 | 2016-01-17 22:36:36 +0100 | [diff] [blame] | 32 | m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!")); |
Wenzel Jakob | 9180519 | 2016-01-17 22:36:43 +0100 | [diff] [blame] | 33 | |
| 34 | /* A fancier default argument */ |
| 35 | std::vector<int> list; |
| 36 | list.push_back(13); |
| 37 | list.push_back(17); |
| 38 | |
| 39 | m.def("kw_func4", &kw_func4, py::arg("myList") = list); |
Wenzel Jakob | 6c03beb | 2016-05-08 14:34:09 +0200 | [diff] [blame] | 40 | m.def("call_kw_func", &call_kw_func); |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 41 | } |