1

In the course of some work I am currently involved in I needed to understand better the content of the .py file which is generated when wrapping C++ using Swig. This is in the context of an existing system (which I did not write) which adds some custom Python that manipulates the content of the globals() in the module. While trying to understand this I realised I did not even understand the 'normal' Swig generated code.

Suppose, for example, we are creating a module, MyModule, and in this we wrap a C++ function void f(). The following will appear in the Swig-generated Python file MyModule.py:

def f():
    return _MyModule.f()
f = _MyModule.f

My question is: what is the point of the first two lines of the above? The entry for 'f' that is added to MyModule's globals() by those first two lines is immediately overwritten by the third line, which I believe is essentially equivalent to the preceding def f().

Am I missing something?

Bob
  • 195
  • 1
  • 11

1 Answers1

1

Your analysis is right - the assignment on the third line you showed completely hides the first two.

That's true in the simple case, however there are times when it doesn't happen. Take for example this SWIG file:

%module test

%pythonprepend %{
#hello world
%}

void foo();

Here the python definition of foo() doesn't get hidden like in your example, because there is extra python code in the generated function. (Even if it's just a comment).

I think the reason the definition is always emitted, rather than just when needed is probably historical, although I can't find an exact example from quickly looking. SWIG supports generating Python code in a lot of different ways for a lot of different versions of Python. (See for example the code generated by -builtin, or the output of -python -help to get some idea of the magnitude of variations. So probably either those assignments were once inside a runtime test that got removed when it was obsoleted and/or it's a hangover from a distant past.

Even in the modern case though having the definition of the method visible in the .py file does still have one substantial benefit, which is that an IDE can do things like count the arguments, read their names and the document string etc. still.

Flexo
  • 87,323
  • 22
  • 191
  • 272