Open In App

Python Inner Functions

Last Updated : 22 Oct, 2024
Summarize
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, etc.

Note: To learn more about first-class functions, please refer to this article: Python – First Class Function

Inner functions

A function defined inside another function is known as an inner function or a nested function. Nested functions can 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.

Example:

Python
# 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
# Python program to illustrate 
# nested functions 
def outerFunction(text): 
    text = text 
  
    def innerFunction(): 
        print(text) 
  
    innerFunction()

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
# 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

In the above example, it can be seen that it is similar to accessing the global variable from a function.


Using an iterable:

Python
# 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
# 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
# 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
# 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
# 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.





Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg
  翻译: