Is nested function a good approach when required by only one function?

nukl picture nukl · Jan 28, 2011 · Viewed 243.4k times · Source

Let's say that a function A is required only by function B, should A be defined inside B?

Simple example. Two methods, one called from another:

def method_a(arg):
    some_data = method_b(arg)

def method_b(arg):
    return some_data

In Python we can declare def inside another def. So, if method_b is required for and called only from method_a, should I declare method_b inside method_a? like this :

def method_a(arg):
    
    def method_b(arg):
        return some_data

    some_data = method_b(arg)

Or should I avoid doing this?

Answer

user225312 picture user225312 · Jan 28, 2011
>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
... 
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4

Is this what you were looking for? It's called a closure.