Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Function in Python

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?

like image 875
Hosam Aly Avatar asked Oct 19 '09 14:10

Hosam Aly


People also ask

What is an example of a nested 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.

What does a nested function do?

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.

Should I use nested functions Python?

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.

How do you use nested methods in Python?

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.


1 Answers

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.

like image 75
Adam Rosenfield Avatar answered Sep 21 '22 17:09

Adam Rosenfield