Discussion:
[Swig-devel] Variable number of input arguments in Python?
Joel Andersson
2016-02-20 19:02:37 UTC
Permalink
Hello,

Is there a clean way (e.g. a feature) to mark that a function should have
variable number of arguments on the Python side, but not on the C/C++ side?
My use case is a function that takes an std::vector<MyClass> on the C++
side, but on the Python side, the natural syntax is to pass a variable
number of inputs.

That is, generate a function such as:

def mywrapper(*arg):
...

instead of
def mywrapper(arg):
...


Best regards,
Joel
William S Fulton
2016-06-04 13:31:39 UTC
Permalink
Post by Joel Andersson
Hello,
Is there a clean way (e.g. a feature) to mark that a function should have
variable number of arguments on the Python side, but not on the C/C++ side?
My use case is a function that takes an std::vector<MyClass> on the C++
side, but on the Python side, the natural syntax is to pass a variable
number of inputs.
...
instead of
...
Presumably you know that you can pass a Python list instead of a
wrapped std::vector to something like mywrapper?

One other suggestion to consider is to use %pythoncode to provide a
method taking *arg and then convert to a python list.

What you want to do doesn't quite fit into the basic concept that SWIG
has, that is, wrapping types individually in a method. You want to
treat the whole function and all its parameters in a different way. In
order to use *arg, the std::vector parameter needs to be the last
parameter in the list like C varargs.

Have you read the varargs chapter http://swig.org/Doc3.0/Varargs.html.
You may get some ideas in there and consider changing the signature of
the method that SWIG sees to be different to the one that the C++
compiler sees, so change from mywrapper(std::vector<MyClass>) to
mywrapper(...) and use some vararg typemaps for what you want.

Personally, I'd just use a Python list as that is near enough the same
thing and more natural in my view!

William

Loading...