Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it good to use nested functions in Python?

Tags:

python

I'm not referring to closures, where the outer function returns the inner function, or to memoization, specifically. There have been a few instances where I've wanted to write a recursive function, perhaps with memoization, and it seemed much simpler to initialize a dictionary or some other data structures in the outer function, and then have a recursive helper function writing to and accessing the dict and the arguments of the outer function. Here's what I mean --

def foo(arr, l):
   cache = {}
   result = []

   def recursive_foo_helper(i, j, k):
      # some code that depends on arr, l, i, j, k, cache, and result

   for (x, y) in arr:
      if recursive_foo_helper(x, y, k):
         return result
   return None

instead of having the helper function declared separately with some super long signature like,

recursive_foo_helper(arr, l, i, j, k, cache={}, result=[])

I have read that doing this is pretty standard for memoization, but I was curious if there's a consensus on whether it's OK to do just for recursive helper functions.

like image 870
lightlike Avatar asked Jun 10 '13 22:06

lightlike


People also ask

When should I use nested function?

Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.

Is it good to use nested functions Python?

Unless you need to hide your functions from the outside world, there's no specific reason for them to be nested. You could define those functions as private top-level functions, and you'd be good to go. In this section, you'll learn about closure factory functions.

Is it good practice to use nested functions?

no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.

Are nested functions faster?

Finding the nested function may be faster because it's stored in the local scope.


2 Answers

There are a lot of good reasons. Personally, I often use nested functions to keep the namespace clean. It's especially useful within object methods :

class Foo(object):
    def bar(self):
        def baz(val):
            return val
        return [ baz(i) for i in range(1,101) ]

If I declare baz outside of bar, I either need to make it a method of Foo, or expose it to the entire package.

like image 161
Jonathan Vanasco Avatar answered Oct 14 '22 23:10

Jonathan Vanasco


I use a nested function to find matches from a list:

def get_exact(data, key, match):
    def is_match(item):
        if (key in item) and (item[key].lower() == match.lower()):
            return item
        return False
    return [i for i in data if is_match(i)]

No other calls in the project have a need to use is_match(item), so why declare it separately?

However, I will say that, for my example, declaring is_match() outside of get_exact() does run around ~0.04 seconds faster in 10,000 iterations.

def is_match(item, key, match):
    if (key in item) and (item[key].lower() == match.lower()):
        return item
    return False

def get_exact(data, key, match):
    return [i for i in data if is_match(i, key, match)]
like image 29
bnlucas Avatar answered Oct 14 '22 23:10

bnlucas