• Jason Rhinelander's avatar
    feat: allow kw-only args after a py::args (#3402) · e7c9753f
    Jason Rhinelander authored
    
    
    * 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: default avatarHenry Schreiner <HenrySchreinerIII@gmail.com>
    Co-authored-by: default avatarHenry Schreiner <HenrySchreinerIII@gmail.com>
    e7c9753f
test_kwargs_and_defaults.cpp 7.42 KB