Inner / Nested Function in Python


Defining a function inside another function is called inner or nested function. Nested function can access the local variables of the enclosing scope.

def outerFunction():
    var = "Hello"
    def innerFunction():
        #using non-local variable var
        print(var)

    innerFunction()

outerFunction()
                
OUTPUT
Hello

As we can see that when we are calling outerFunction, innerFunction is executing and able to access the non-local variable var.

Non-Local Variable :

The local variable var of the outer function is a non-local variable for the inner function which it can access but not modify.

Example : try to modify the non-local variable in inner-function.

def outerFunction():
    var = "Hello"
    def innerFunction():
        var = "Hi"
        print(var)

    innerFunction()
    print(var)
outerFunction()
                
OUTPUT
Hi
Hello

As we can see in the above program, trying to modify the non-local variable var inside the innerFunction, but it is not getting modified. We can clearly see that after the execution of innerFunction, getting the the value of var as 'Hello'.

This happens due to variable scopes rule defined in the Python.

Now, if we want to modify the non-local variables inside the inner function then first we must declare them explicitly as non-local using nonlocal keyword.

def outerFunction():
    var = "Hello"
    def innerFunction():
        nonlocal var
        var = "Hi"
        print(var)

    innerFunction()
    print(var)
outerFunction()
                
OUTPUT
Hi
Hi

Another way to modify non-local variables, see the code below

def outerFunction():
    outerFunction.var = "Hello"
    
# declare the variable using function name
    def innerFunction():
        outerFunction.var = "Hi"
        print(outerFunction.var)

    innerFunction()
    print(outerFunction.var)

outerFunction()
                
OUTPUT
Hi
Hi

Use of Nested Function:

To understand and implement the concept of closures and decorators, you must know the concept of nested function.

Next chapter is Anonymous Function





Video Lecture



 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-8527238801 , +91-9451396824

© 2017, prowessapps.in, All rights reserved