blob: 4b3c6d08bc5fd8aa3bbcd303a147ae72408ba44d [file] [log] [blame]
Wenzel Jakoba576e6a2015-07-29 17:51:54 +02001/*
2 example/example11.cpp -- keyword arguments and default values
3
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02004 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakoba576e6a2015-07-29 17:51:54 +02005
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 Jakob91805192016-01-17 22:36:43 +010011#include <pybind11/stl.h>
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020012
13void kw_func(int x, int y) { std::cout << "kw_func(x=" << x << ", y=" << y << ")" << std::endl; }
14
Wenzel Jakob91805192016-01-17 22:36:43 +010015void 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 Jakob178c8a82016-05-10 15:59:01 +010022py::object call_kw_func(py::function f) {
Wenzel Jakob6c03beb2016-05-08 14:34:09 +020023 py::tuple args = py::make_tuple(1234);
24 py::dict kwargs;
25 kwargs["y"] = py::cast(5678);
Wenzel Jakob178c8a82016-05-10 15:59:01 +010026 return f(*args, **kwargs);
27}
28
29void args_function(py::args args) {
Yung-Yu Chen114bfeb2016-05-25 20:54:12 +080030 for (size_t it=0; it<args.size(); ++it)
31 std::cout << "got argument: " << py::object(args[it]) << std::endl;
Wenzel Jakob178c8a82016-05-10 15:59:01 +010032}
33
34void args_kwargs_function(py::args args, py::kwargs kwargs) {
35 for (auto item : args)
36 std::cout << "got argument: " << item << std::endl;
37 if (kwargs) {
38 for (auto item : kwargs)
39 std::cout << "got keyword argument: " << item.first << " -> " << item.second << std::endl;
40 }
Wenzel Jakob6c03beb2016-05-08 14:34:09 +020041}
42
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020043void init_ex11(py::module &m) {
44 m.def("kw_func", &kw_func, py::arg("x"), py::arg("y"));
45 m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200);
Wenzel Jakob66c9a402016-01-17 22:36:36 +010046 m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!"));
Wenzel Jakob91805192016-01-17 22:36:43 +010047
48 /* A fancier default argument */
49 std::vector<int> list;
50 list.push_back(13);
51 list.push_back(17);
52
53 m.def("kw_func4", &kw_func4, py::arg("myList") = list);
Wenzel Jakob6c03beb2016-05-08 14:34:09 +020054 m.def("call_kw_func", &call_kw_func);
Wenzel Jakob178c8a82016-05-10 15:59:01 +010055
56 m.def("args_function", &args_function);
57 m.def("args_kwargs_function", &args_kwargs_function);
Dean Moldovan96017dd2016-06-03 10:00:40 +020058
59 using namespace py::literals;
60 m.def("kw_func_udl", &kw_func, "x"_a, "y"_a=300);
Jerry Gamachec6e0cdf2016-06-15 12:48:15 -040061 m.def("kw_func_udl_z", &kw_func, "x"_a, "y"_a=0);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020062}