Look at two ways of structuring my functions:
class myClass:
def _myFunc(self):
pass
def myFunc2(self):
self._myFunc()
class myClass:
def myFunc2(self):
def myFunc():
pass
myFunc()
Will the second option be slower?
I only need to call myFunc from myFunc2, so ‘d like to hide it from my module documentation, I could use an underscore for that, but I thought it would be cleaner to have it inside the function. On the other hand I might need to call myFunc2 few hundred times per second, so “redefining” myFunc when calling myFunc2 each time might be slow… is that a good guess?
The local function in the second variant won’t be compiled over and over again — it is compiled once together with the whole file, and its body is stored in a code object. The only thing that happens during the execution of the outer function is that the code object is wrapped in a new function object which is then bound to the local name
myFunc.There might be a difference between the two variants if
myFunc()takes default parameters. Their definition would be executed over and over again in the second variant, resulting in a possible performance hit.Exaggerated example:
With the daft code above,
myClass.myFunc2()will return immediately, whilemyClass2.myFunc2()takes a second to execute.