pybind11/docs/advanced
Jason Rhinelander e7c9753f1d
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling

This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).

* Allow keyword-only arguments to follow py::args

This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:

    def f(a, *args, b):
        return a * b + sum(args)

    f(10, 1, 2, 3, b=20)  # == 206

With this change, you can bind such a function using:

    m.def("f", [](int a, py::args args, int b) { /* ... */ },
        "a"_a, "b"_a);

Or, to be more explicit about the keyword-only arguments:

    m.def("g", [](int a, py::args args, int b) { /* ... */ },
        "a"_a, py::kw_only{}, "b"_a);

(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).

This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.

* Take args/kwargs by const lvalue ref

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-28 23:16:55 -04:00
..
cast Add blacken-docs and pycln pre-commit hooks (#3292) 2021-09-22 15:38:50 -04:00
pycpp fix: deprecate make_simple_namespace, fix Python 3.11 (#3374) 2021-10-19 14:39:29 -04:00
classes.rst maint: Add additional linter-related pre-commit hooks (#3337) 2021-10-08 08:38:04 -04:00
embedding.rst maint: Add additional linter-related pre-commit hooks (#3337) 2021-10-08 08:38:04 -04:00
exceptions.rst feat: Add C++ binding to throw AttributeError (#3387) 2021-10-23 00:07:22 -04:00
functions.rst feat: allow kw-only args after a py::args (#3402) 2021-10-28 23:16:55 -04:00
misc.rst maint: Add additional linter-related pre-commit hooks (#3337) 2021-10-08 08:38:04 -04:00
smart_ptrs.rst Add blacken-docs and pycln pre-commit hooks (#3292) 2021-09-22 15:38:50 -04:00