Search code examples
pythonnested-function

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?


Solution

  • 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.