What benefit or implications could we get with Python code like this:
class some_class(parent_class): def doOp(self, x, y): def add(x, y): return x + y return add(x, y)
I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothing outside it except calling it. (The actual code can be found here.) Why might someone code it like this? Is there some benefit or side effect for writing the code inside the nested function rather than in the outer, normal function?
Users typically create nested functions as part of a conditional formula. For example, IF(AVERAGE(B2:B10)>100,SUM(C2:G10),0). The AVERAGE and SUM functions are nested within the IF function.
A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.
When coding we want to hide immaterial detail. E.g. we mark functions as private as much as we can (well in python we can't really, so we use a leading underscore convention _like_this ). So that's a good reason to use nested functions — help the reader understand that the logic of bar will not be used anywhere else.
Nested method accepts two arguments and performs addition and multiplication of those arguments and prints the result. Remember that in order for nested method to execute, you need to call it from inside the outer method. You can call it as many times as you want from inside the outer method.
Normally you do it to make closures:
def make_adder(x): def add(y): return x + y return add plus5 = make_adder(5) print(plus5(12)) # prints 17
Inner functions can access variables from the enclosing scope (in this case, the local variable x
). If you're not accessing any variables from the enclosing scope, they're really just ordinary functions with a different scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With