문제

I'm delving inside the code for WiringPi-Python for Python and I found several blocks like this:

def wiringPiSetup():
  return _wiringpi2.wiringPiSetup()
wiringPiSetup = _wiringpi2.wiringPiSetup

This is a bit puzzling for me because I think that this:

def wiringPiSetup():
  return _wiringpi2.wiringPiSetup()

would yield exactly the same result as this:

wiringPiSetup = _wiringpi2.wiringPiSetup

I know that the first is declaring a new function, and the second is a reference to the original function, but in the tests I've made I find they are totally equivalent. Look here:

>>> def a():
...     return 4
... 
>>> def a1():
...     return a()
... 
>>> a2 = a
>>> 
>>> a1()
4
>>> a2()
4

So, why does WiringPi-Python put both when any of them will suffice?

BTW:

  • I'm using Python 2.7.3
  • This is the file where I saw that: here
도움이 되었습니까?

해결책

The file is generated by SWIG. The function definitions are indeed 'dead code', in that you can remove the function definition altogether and just leave the assignment in place.

Because the code is autogenerated, the code is somewhat inefficient. The SWIG function that generates this code, states:

if (Getattr(n, "feature:python:callback") || !have_addtofunc(n)) {
  /* If there is no addtofunc directive then just assign from the extension module (for speed up) */
  Printv(f_dest, name, " = ", module, ".", name, "\n", NIL);
}

so the second assignment is there to just replace the generated Python function to speed up usage.

If the function has additional Python code to add when generating (have_addtofunc() is true when there is a docstring, a prepend or an append value) then the replacement line isn't generated.

Presumably the original function is left in place so that auto-completion tools can make use of the function signature.

다른 팁

This file was generated by SWIG. From reading SWIG Python generator soure code (emitFunctionShadowHelper) it seems the code generator creates a wrapper function if the wrapped function has some docstring, but then if the function does not has any docstring then the code generator issues a simple assign statement. It seems like an "else" clause might be added to the that function.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top