Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG generates invalid Python wrapper code

Tags:

python

swig

It is a wierd problem that sometimes happens when I use SWIG to generate a Python wrappers. It happens with both Swig 2.x and 3.x versions. I don't know what triggers it, but sometimes after code refactoring, this error appears.

The problem is that SWIG generates code that is not valid Python, but some kind of pseudo-code. For example

class SwigPyIterator(_object):

    ... note that method definitions are not Python:

    def value(self) -> "PyObject *" : return _vabamorf.SwigPyIterator_value(self)
    def incr(self, n : 'size_t'=1) -> "swig::SwigPyIterator *" : return _vabamorf.SwigPyIterator_incr(self, n)
    def decr(self, n : 'size_t'=1) -> "swig::SwigPyIterator *" : return _vabamorf.SwigPyIterator_decr(self, n)

I am using setuptools and here are the lines relevant to SWIG:

swigging estnltk/pyvabamorf/vabamorf.i to estnltk/pyvabamorf/vabamorf_wrap.cpp
swig -python -c++ -py3 -o estnltk/pyvabamorf/vabamorf_wrap.cpp estnltk/pyvabamorf/vabamorf.i

Does anyone know, what triggers this behaviour and how to fix it? I have been able to fix this in the past, but I have never been able to trace down specific changes that made this problem disappear.

like image 457
Timo Avatar asked Mar 08 '26 09:03

Timo


1 Answers

Ok, this was a stupid user error. This was actually expected behavior and this pseudo-code is actually something called function annotations.

It is also documented in SWIG documentation

The -py3 option will enable function annotation support. When used SWIG is able to generate proxy method definitions like this:

  def foo(self, bar : "int" = 0) -> "void" : ...

It seems I managed to confuse myself not cleaning all files between Python2/Python3 compiles and got distracted also by some import related errors introduced during refactoring.

like image 169
Timo Avatar answered Mar 09 '26 22:03

Timo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!