Open In App

Python Inner Functions

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 functio

n. 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:

Python3 1==
# 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:

Python3 1==
# 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:

Python3 1==
# 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.

Python3 1==
# 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 – Python3 1==
    # 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 – Python3 1==
    # 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. Python3 1==
    # 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.
Python3 1==
# 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.
Python3 1==
# 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 + y 
  
def sub(x, y): 
    return x-y 
  
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


Python Inner Functions – FAQs

What are the inbuilt functions in Python?

Python provides a wide range of inbuilt functions, such as print(), len(), type(), int(), str(), list(), dict(), input(), sum(), min(), max(), and many others. These functions are available by default and do not require any additional imports.

What goes inside a function in Python?

Inside a function in Python, you typically define:

  • Function parameters: Variables that take input values.
  • Docstring: An optional string to describe the function’s purpose.
  • Body: The code that performs the function’s tasks, including any calculations, operations, or logic.
  • Return statement: The value or values the function returns after execution.

Example:

def greet(name):
"""Function to greet a person by name."""
greeting = f"Hello, {name}!"
return greeting

Why use inner class in Python?

Inner classes are used in Python for several reasons:

  • Encapsulation: To encapsulate a class within another class, providing a better structure and hiding the inner class from external access.
  • Logical grouping: To group related classes together, making the code more modular and easier to understand.
  • Access to outer class: Inner classes can access the members of the outer class, which can be useful in certain design patterns.

    What functions are inside __init__ in Python?

    The __init__ method in Python is the initializer method for a class. It is used to initialize the instance variables of a class when an object is created. Inside __init__, you can:

    • Initialize attributes: Set the initial state of the object.
    • Perform setup tasks: Execute any setup code required for the object.

    Example:

    class Person:
    def __init__(self, name, age):
    self.name = name
    self.age = age

      What is the best practice for function inside function in Python?

      Best practices for defining functions inside functions in Python include:

      • Encapsulation: Use inner functions to encapsulate functionality that is only relevant within the outer function.
      • Closure: Inner functions can capture and remember the state of the outer function’s variables, creating closures.
      • Readability: Ensure the inner function improves code readability and maintainability.

      Example:

      def outer_function(x):
      def inner_function(y):
      return x + y
      return inner_function

      add_five = outer_function(5)
      result = add_five(10) # result is 15

      In this example, inner_function is defined within outer_function, capturing the value of x and creating a closure.



      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 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 [GFGTABS] Python # create a Geeksforgeeks class class Geeksfo
      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
      Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
      Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
      3 min read
      Mathematical Functions in Python | Set 4 (Special Functions and Constants)
      Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
      2 min read
      Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
      Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
      4 min read
      Array in Python | Set 2 (Important Functions)
      Array in Python | Set 1 (Introduction and Functions)Array in Python | Set 2Below are some more useful functions provided in Python for arrays: Array Typecode FunctionThis function returns the data type by which the array is initialized. In this example, we are using arr.typecode to find out the data type of array initialization. C/C++ Code # import
      3 min read
      Bisect Algorithm Functions in Python
      The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module "bisect" which allows keeping the list in sorted order after the insertion of each element. This is essential as this reduces overhead time required to
      5 min read
      Python | Set 2 (Variables, Expressions, Conditions and Functions)
      Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
      3 min read
      Python | Functions | Question 4
      What is the output of the following program : y = 8 z = lambda x : x * y print (z(6)) (A) 48 (B) 14 (C) 64 (D) None of the above Answer: (A) Explanation: lambdas are concise functions and thus, result = 6 * 8Quiz of this Question
      1 min read
      Python | Functions | Question 5
      What is called when a function is defined inside a class? (A) Module (B) Class (C) Another Function (D) Method Answer: (D)Explanation: Explanation: When a function is defined inside a class then it is called Method. The method is accessible to data that is contained within the class. Quiz of this QuestionPlease comment below if you find anything wr
      1 min read
      Python | Functions | Question 6
      Which of the following is the use of id() function in python? (A) Id returns the identity of the object (B) Every object doesn’t have a unique id (C) All of the mentioned (D) None of the mentioned Answer: (A) Explanation: Each object in Python has a unique id. The id() function returns the object’s id.Quiz of this QuestionPlease comment below if yo
      1 min read
      Python | startswith() and endswith() functions
      Python library provides a number of built-in methods, one such being startswith() and endswith() functions which are used in string related operations. Startswith() Syntax: str.startswith(search_string, start, end) Parameters : search_string : The string to be searched. start : start index of the str from where the search_string is to be searched.
      2 min read
      maketrans() and translate() functions in Python
      In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article. maketrans() maketrans() function is used to construct the transition table i.e specify the
      3 min read
      Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
      In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them
      3 min read
      Python bit functions on int (bit_length, to_bytes and from_bytes)
      The int type implements the numbers.Integral abstract base class. 1. int.bit_length() Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros. Code to demonstrate num = 7 print(num.bit_length()) num = -7 print(num.bit_length()) Output: 3 3 2. int.to_bytes(length, byteorder, *, signed=False) Return
      1 min read
      Difference between input() and raw_input() functions in Python
      Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt )raw_input ( prompt )input() function Pytho
      4 min read
      turtle.setpos() and turtle.goto() functions in Python
      The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.setpos() This method is used to move the turtle to an absolute position. This method has Aliases: setpos, setposition, goto. S
      1 min read
      Why and how are Python functions hashable?
      So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set. An object is h
      2 min read
      Executing functions with multiple arguments at a terminal in Python
      Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line argument
      4 min read
      Python Regex - re.MatchObject.start() and re.MatchObject.end() functions
      In this article, we are going to see re.MatchObject.start() and re.MatchObject.end() regex methods. re.MatchObject.start() This method returns the first index of the substring matched by group. Syntax: re.MatchObject.start([group]) Parameter: group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists b
      2 min read
      How to store Python functions in a Sqlite table?
      SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
      3 min read
      Understanding Recursive Functions with Python
      Recursion is characterized as the process of describing something in terms of itself; in other words, it is the process of naming the function by itself. Recursion is the mechanism of a function calling itself directly or implicitly, and the resulting function is known as a Recursive function. Advantages:Code reusabilityEasily understandableTime co
      3 min read
      Timing Functions With Decorators - Python
      Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are going to see the timing function with decorators. D
      4 min read
      How to Write Spark UDF (User Defined Functions) in Python ?
      In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our
      4 min read
      Python - Create or Redefine SQLite Functions
      The SQLite does not have functions or stored procedure language like MySQL. We cannot create stored functions or procedures in SQLite. That means the CREATE FUNCTION or CREATE PROCEDURE does not work in SQLite. In SQLite instead of CREATE FUNCTION or CREATE PROCEDURE we have SQLite’s C API which allows us to create our own user-defined functions, o
      3 min read
      Article Tags :
      Practice Tags :