[C++-sig] Boost.Python v2: keyword arguments

David Abrahams dave at boost-consulting.com
Sat Sep 28 10:04:00 CEST 2002

I have just checked in keyword argument support for Boost.Python v2

Boost.Python v2 is now feature-complete for release!


Keywords are specified as:

    args("param1", "param2", "param3")

If N keywords are supplied, they specify the argument names of the last N
parameters to the function.

The following interfaces:

    def("function_name", function, ... )

        .def("method_name", &T::method, ... )

Now accept up to 3 arguments in any order in place of ...

    docstring (a string literal)
    call policies

Keywords can also be supplied in:

    init<T1, T2...>("docstring", keywords)
    init<T1, T2...>(keywords, "docstring")
    init<T1, T2...>(keywords)

and likewise in the constructor of overload dispatchers defined with


See libs/python/test/args.[py/cpp] for examples.

Note that keyword arguments are really useful for cases like this:

    >>> def f(a = 1, b = 2, c = 3, d = 4, e = 5, f = 6):

    >>> f(1, 2, f = 99)  # **

But we can't support that with the BOOST_PYTHON_[MEMBER_]FUNCTION_OVERLOADS
mechanism. It's a limitation of C++. Our current default argument mechanism
creates overloaded Python functions which invoke a C++ function call
expression, and they have no access to the expressions used for any default
arguments to the C++ function. So:

 void ff(int a = 1, int b = 2, int c = 3, int d = 4, int e = 5, int f = 6)

Challenge: now write down a piece of valid C++ code which corresponds to
**. You can't do it without knowing and using the default argument
expressions for c, d, e. But remember, the library has no access to those.

We can allow you to specify any initial section of the total argument set
in any order, but how useful is that?

So, I plan to allow this instead:

    def("f", &f, (arg("a") = 1, arg("b") = 2, arg("c") = 3, ...)); // ***

which gets around that problem by supplying defaults up-front. The
downside, of course, is that you have to keep those expressions in-synch
with your C++ code. This feature will be added shortly after the first
release. All the infrastructure is already there.


           David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com

More information about the Cplusplus-sig mailing list