Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in these two Python statements?

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
like image 942
Daniel Avatar asked Oct 01 '22 22:10

Daniel


1 Answers

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.

like image 81
Martijn Pieters Avatar answered Oct 17 '22 15:10

Martijn Pieters