Python | Access function inside a function

Let us take a look at how this can be done in Python.

Example 1:

def outer_func():
    def inner_func():
        print("Hello! How are you?")



We define inner functions—also referred to as nested functions—within other functions. The variables and names declared in the enclosing function are directly accessible to this type of function in Python. The most common usage for inner functions is as closure factories and decorator functions.

On print the message Hello! How are you? to the screen, you declare inner_func() within outer_func() in this code. On the final line of outer func, you must call inner_func() to do it. The easiest approach to creating an inner function in Python is as described above.

Example 2:

def get_power(exponent):
    def power(base):
        return base ** exponent
    return power


What’s occurring in this function is as follows: get_power(), a closure factory function, is created at line 3. This implies that each time it is called, a new closure is created, and it then returns the new closure to the caller. Line 4 declares the inner function power(), which returns the value of the expression base**exponent given a single parameter, base. Without invoking it, line 6 returns power as a function object.

Here is the end of this article. Python nested functions are a very important concept and here we have tried out best to explain to you in the simplest way possible using an example.


Author: Ayush Purawr