avatarLaxfed Paulacy

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2646

Abstract

<span class="hljs-title">mug</span>(<span class="hljs-string">"coffee"</span>)</span></pre></div><p id="9270">When <code>mug("coffee")</code> is called, it prints "I like coffee" because the inner function <code>inside()</code> has access to the variable <code>stuff</code> from the containing function <code>mug()</code>.</p><h2 id="7595">Recursive Function Using Inner Function</h2><p id="93d5">A recursive function is one that calls itself. Here’s an example of a recursive function using an inner function to calculate a factorial:</p><div id="ce0b"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">first_factorial</span>(<span class="hljs-params">num</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">_recurse_factorial</span>(<span class="hljs-params">n</span>): <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">isinstance</span>(n, <span class="hljs-built_in">int</span>) <span class="hljs-keyword">or</span> n < <span class="hljs-number">0</span>: <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Input must be a positive integer"</span>) <span class="hljs-keyword">if</span> n <span class="hljs-keyword">in</span> (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>): <span class="hljs-keyword">return</span> <span class="hljs-number">1</span> <span class="hljs-keyword">return</span> n * _recurse_factorial(n - <span class="hljs-number">1</span>)

<span class="hljs-keyword">return</span> _recurse_factorial(num)

result = first_factorial(<span class="hljs-number">4</span>) <span class="hljs-built_in">print</span>(result) <span class="hljs-comment"># Output: 24</span></pre></div><h2 id="590b">Refactoring Using Inner Function</h2><p id="4089">You can refactor a function to use an inner function for encapsulation. Here’s a refactored version of the factorial function:</p><div id="8f7b"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">second_factorial</span>(<span class="hljs-params">num</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">_recurse_factorial</span>(<span class="hljs-params">n</span>): <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">isinstance</span>(n, <span class="hljs-built_in">int</span>) <span class="hljs-keyword">or</span> n < <span class="hljs-number">0</span>: <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string

Options

">"Input must be a positive integer"</span>) <span class="hljs-keyword">if</span> n <span class="hljs-keyword">in</span> (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>): <span class="hljs-keyword">return</span> <span class="hljs-number">1</span> <span class="hljs-keyword">return</span> n * _recurse_factorial(n - <span class="hljs-number">1</span>)

<span class="hljs-keyword">return</span> _recurse_factorial(num)

result = second_factorial(<span class="hljs-number">4</span>) <span class="hljs-built_in">print</span>(result) <span class="hljs-comment"># Output: 24</span></pre></div><h2 id="6641">Inner Functions vs. Private Helper Functions</h2><p id="278e">Whether to use an inner function or a private helper function in the module is a matter of preference and reuse. If there’s a chance that the function could be used by any other function, it should be a private helper function. Here’s an example of refactoring to use a private helper function instead of an inner function:</p><div id="ce52"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">process_hotspots</span>(<span class="hljs-params">file</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">_most_common_provider</span>(<span class="hljs-params">file_obj</span>): <span class="hljs-comment"># Implementation</span> <span class="hljs-keyword">pass</span>

<span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(file, <span class="hljs-built_in">str</span>):
    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(file, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
        _most_common_provider(f)
<span class="hljs-keyword">else</span>:
    _most_common_provider(file)

<span class="hljs-comment"># Call process_hotspots with a file name or file handle</span></pre></div><h2 id="3f5a">Conclusion</h2><p id="05cd">In this article, we learned about Python inner functions and their use cases. You can use inner functions for encapsulation and to modularize your code. Understanding inner functions is essential for mastering closures in Python.</p><p id="af75">Now that you understand inner functions, you can move on to their primary use: closures.</p><figure id="e43d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*6BSFGME1IbhVbZ65.jpeg"><figcaption></figcaption></figure><p id="ab76"><a href="https://readmedium.com/python-step-out-over-python-abc3bceb8005">PYTHON — Step Out Over Python</a></p></article></body>

PYTHON — Basics of Python Inner Functions

Privacy is not something that we’re merely entitled to, it’s an absolute prerequisite. — Marlon Brando

PYTHON — Multiple Expressions in Lambda Functions in Python

## The Basics of Python Inner Functions

Python inner functions are functions defined inside other functions. They have access to the variables in the scope of their containing functions. In this article, we will explore inner functions through practical examples and discuss their primary use: closures.

Let’s start by looking at a simple example of an inner function.

def outer_function():
    print("This is the outer function")

    def inner_function():
        print("This is the inner function")

    inner_function()

outer_function()

When you run the above code, you will see that the inner function is called from within the outer function, and both messages are printed.

Accessing Variables in the Containing Function’s Scope

Inner functions have access to the variables in the scope of their containing functions. Here’s an example to demonstrate this:

def mug(stuff):
    def inside():
        print(f"I like {stuff}")

    inside()

mug("coffee")

When mug("coffee") is called, it prints "I like coffee" because the inner function inside() has access to the variable stuff from the containing function mug().

Recursive Function Using Inner Function

A recursive function is one that calls itself. Here’s an example of a recursive function using an inner function to calculate a factorial:

def first_factorial(num):
    def _recurse_factorial(n):
        if not isinstance(n, int) or n < 0:
            raise ValueError("Input must be a positive integer")
        if n in (0, 1):
            return 1
        return n * _recurse_factorial(n - 1)

    return _recurse_factorial(num)

result = first_factorial(4)
print(result)  # Output: 24

Refactoring Using Inner Function

You can refactor a function to use an inner function for encapsulation. Here’s a refactored version of the factorial function:

def second_factorial(num):
    def _recurse_factorial(n):
        if not isinstance(n, int) or n < 0:
            raise ValueError("Input must be a positive integer")
        if n in (0, 1):
            return 1
        return n * _recurse_factorial(n - 1)

    return _recurse_factorial(num)

result = second_factorial(4)
print(result)  # Output: 24

Inner Functions vs. Private Helper Functions

Whether to use an inner function or a private helper function in the module is a matter of preference and reuse. If there’s a chance that the function could be used by any other function, it should be a private helper function. Here’s an example of refactoring to use a private helper function instead of an inner function:

def process_hotspots(file):
    def _most_common_provider(file_obj):
        # Implementation
        pass

    if isinstance(file, str):
        with open(file, 'r') as f:
            _most_common_provider(f)
    else:
        _most_common_provider(file)

# Call process_hotspots with a file name or file handle

Conclusion

In this article, we learned about Python inner functions and their use cases. You can use inner functions for encapsulation and to modularize your code. Understanding inner functions is essential for mastering closures in Python.

Now that you understand inner functions, you can move on to their primary use: closures.

PYTHON — Step Out Over Python

Basics
Python
ChatGPT
Inner
Functions
Recommended from ReadMedium