简体   繁体   中英

swig C++->Python 2.X conversion and method's arguments

I am using the Eric IDE for Python. It is using autocompletion and it should be very useful. But, we develop python scripts that use objects from a C++ library that we convert using Swig. Unfortunately, swig create a .py file that maps each C++ object's method replacing all arguments with an *args unique argument and so Eric's autocompletion is not as useful as it may be as it does not display the list of parameters but only that args which is useless.

For instance, I have a C++ .h file :

 #ifdef SWIG
 %module testPy
 %{
    #include "testPy.h"
 %}
 %feature("autodoc","0");
 #endif //SWIG
 class IntRange
 {
   public:
     bool contains(int value) const;
 };

I generate the .py file by :

 swig3.0 -c++ -python testPy.h

and the generated .py file contains :

  def contains(self, *args):
    """contains(self, value) -> bool"""
    return _testPy.IntRange_contains(self, *args)

So the autodoc part is fine. Unfortunately, it is not used by Eric and the arguments of the method have been replaced by *args.

Is there a way to ask swig to keep the arguments' names?

NB : I am using Python 2.7 and swig 3.0.2

According the the Swig Changelog , Python named parameters are available from version 3.0.3.

One thing that may make autocompletion more intelligent is to have docstrings generated. I am not familiar with Eric so I don't know if it uses these in autocompletion, but some editors do and show you original type information if that information is in the doc string of a method. You enable this by setting the autodoc feature:

%feature("autodoc", "0");

The number can go up to 3 and determines how verbose/informative the docstrings are. For instance, with level three, the following C++ method:

class IntRange
{
public:
  bool contains(int value) const;
};

results in the following Python code:

def contains(self, value):
    """
    contains(IntRange self, int value) -> bool

    Parameters
    ----------
    value: int

    """
    return _foo.IntRange_contains(self, value)

I just tried your example (with just this one function), and for me SWIG does preserve the argument names (SWIG 3.0.9).

However, if your function is an overloaded function, then SWIG will always create a wrapper taking *args as you describe, and perform the dispatching in C++.

Using the "autodoc" feature is indeed very useful in this case, since the method signature (with argument names) is placed into the docstring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM