Ethan Bierlein
Ethan Bierlein

Reputation: 3535

Nesting functions inside of functions

Is it possible to nest functions inside of functions? If so, what purposes does it have? I have some example code below to show what I mean.

def theFunction():
    print "This is a function"
    def functionception():
        print "Bad inception joke...."

Once again, is this possible? If so, what purposes does it serve, and how is it used?

Upvotes: 0

Views: 102

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122022

Yes it's possible, and is frequently used when decorating other functions, for example

def memo(f):
    cache = {}
    def func(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return func

Example usage:

@memo
def memoized_func(some_arg):
    return some_arg ** 2

Here the inner function func is used to wrap the argument function f, providing additional functionality (in this case saving the results of previous computations).

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 12092

Yes you can.

You can have the outer function do some boundary condition checks on variables passed to the outer function and pass the "valid/sanitized" variables to the inner function to do the actual processing/manipulation. This is in fact how decorators work.

This blog explains in detail how outer function inner function combination works in decorators - http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/

Upvotes: 3

Related Questions