Inner functions

A function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. To know more about encapsulation click here.

Example:




# Python program to illustrate 
# nested functions 
def outerFunction(text): 
    text = text 
    
    def innerFunction(): 
        print(text) 
    
    innerFunction() 
    
if __name__ == '__main__'
    outerFunction('Hey !'


Output:

Hey!

In the above example, innerFunction() has been defined inside outerFunction(), making it an inner function. To call innerFunction(), we must first call outerFunction(). The outerFunction() will then go ahead and call innerFunction() as it has been defined inside it.

It is important that outer function has to be called, so that the inner function can execute. To demonstrate this consider the below example:
Example:




# Python program to illustrate 
# nested functions 
def outerFunction(text): 
    text = text 
    
    def innerFunction(): 
        print(text) 
    
    innerFunction() 


Output:

This code will return nothing when executed.

Python Inner Functions

In Python, functions are treated as first class objects. First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions.

Properties of first class functions:

  • A function is an instance of the Object type.
  • You can store the function in a variable.
  • You can pass the function as a parameter to another function.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …

Note: To know more about first class objects click here.

Similar Reads

Inner functions

A function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. To know more about encapsulation click here....

Scope of variable in nested function

The location where we can find a variable and also access it if required is called the scope of a variable. It is known how to access a global variable inside a function, but, what about accessing the variable of an outer function? Let’s see an example:...

Python Closures

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory....

Contact Us