Open In App

Python Inner Functions

Last Updated : 25 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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 program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
    s = 'I love GeeksforGeeks'
      
    def f2():
        print(s)
          
    f2()
  
# Driver's code
f1()


Output:

I love GeeksforGeeks

In the above example, it can be seen that it is similar to accessing the global variable from a function. Now let’s suppose you want to change the variable of the outer function.




# Python program to 
# demonstrate accessing of
# variables of nested functions
  
def f1():
    s = 'I love GeeksforGeeks'
      
    def f2():
        s = 'Me too'
        print(s)
          
    f2()
    print(s)
  
# Driver's code
f1()


Output:

Me too
I love GeeksforGeeks

It can be seen the value of the variable of the outer function is not changed. However, the value of the variable of the outer function can be changed. There are different ways to change the value of the variable of the outer function.

  • Using an iterable –




    # Python program to 
    # demonstrate accessing of
    # variables of nested functions
      
    def f1():
        s = ['I love GeeksforGeeks']
          
        def f2():
            s[0] = 'Me too'
            print(s)
              
        f2()
        print(s)
      
    # Driver's code
    f1()

    
    

    Output:

    ['Me too']
    ['Me too']
    
  • Using nonlocal keyword –




    # Python program to 
    # demonstrate accessing of
    # variables of nested functions
      
    def f1():
        s = 'I love GeeksforGeeks'
          
        def f2():
            nonlocal s
            s = 'Me too'
            print(s)
              
        f2()
        print(s)
      
    # Driver's code
    f1()

    
    

    Output:

    Me too
    Me too
    
  • Value can also be changed as shown in the below example.




    # Python program to 
    # demonstrate accessing of
    # variables of nested functions
      
    def f1():
        f1.s = 'I love GeeksforGeeks'
          
        def f2():
            f1.s = 'Me too'
            print(f1.s)
              
        f2()
        print(f1.s)
      
    # Driver's code
    f1()

    
    

    Output:

    Me too
    Me too
    

Python Closures

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

  • It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
  • A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.
    filter_none.




# Python program to illustrate 
# closures 
def outerFunction(text): 
    text = text 
    
    def innerFunction(): 
        print(text) 
    
    return innerFunction # Note we are returning function WITHOUT parenthesis 
    
if __name__ == '__main__'
    myFunction = outerFunction('Hey !'
    myFunction() 


Output:

Hey!
  • As observed from above code, closures help to invoke function outside their scope.
  • The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope.




# Python program to illustrate 
# closures 
import logging 
logging.basicConfig(filename ='example.log', level = logging.INFO) 
    
    
def logger(func): 
    def log_func(*args): 
        logging.info( 
            'Running "{}" with arguments {}'.format(func.__name__, args)) 
        print(func(*args)) 
    # Necessary for closure to work (returning WITHOUT parenthesis) 
    return log_func               
    
def add(x, y): 
    return x +
    
def sub(x, y): 
    return x-
    
add_logger = logger(add) 
sub_logger = logger(sub) 
    
add_logger(3, 3
add_logger(4, 5
    
sub_logger(10, 5
sub_logger(20, 10


Output:

6
9
5
10


Similar Reads

numpy.inner() in python
numpy.inner(arr1, arr2): Computes the inner product of two arrays. Parameters : arr1, arr2 : array to be evaluated. Return: Inner product of the two arrays. Code #1 : # Python Program illustrating # numpy.inner() method import numpy as geek # Scalars product = geek.inner(5, 4) print("inner Product of scalar values : ", product) # 1D array
1 min read
Inheritance in Python Inner Class
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
3 min read
Python - Inner Nested Value List Mean in Dictionary
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The
5 min read
Compute the inner product of vectors for 1-D arrays using NumPy in Python
Python has a popular package called NumPy which used to perform complex calculations on 1-D and multi-dimensional arrays. To find the inner product of two arrays, we can use the inner() function of the NumPy package. Syntax: numpy.inner(array1, array2) Parameters: array1, array2: arrays to be evaluated Returns: Inner Product of two arrays Example 1
2 min read
Compute the inner product of vectors for 1-D arrays using NumPy in Python
Python has a popular package called NumPy which used to perform complex calculations on 1-D and multi-dimensional arrays. To find the inner product of two arrays, we can use the inner() function of the NumPy package. Syntax: numpy.inner(array1, array2) Parameters: array1, array2: arrays to be evaluated Returns: Inner Product of two arrays Example 1
2 min read
Python Pandas - Difference between INNER JOIN and LEFT SEMI JOIN
In this article, we see the difference between INNER JOIN and LEFT SEMI JOIN. Inner Join An inner join requires two data set columns to be the same to fetch the common row data values or data from the data table. In simple words, and returns a data frame or values with only those rows in the data frame that have common characteristics and behavior
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class C/C++ Code # create a Geeksforgeeks class class Geeksforgeeks
5 min read
Calculate inner, outer, and cross products of matrices and vectors using NumPy
Let's discuss how to find the inner, outer, and cross products of matrices and vectors using NumPy in Python. Inner Product of Vectors and Matrices To find the inner product of the vectors and matrices, we can use the inner() method of NumPy.Syntax: numpy.inner(arr1, arr2) Code : C/C++ Code # Python Program illustrating # numpy.inner() method impor
2 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Article Tags :
Practice Tags :