0

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?

3
  • 1
    Yup, they're called decorators. Commented Apr 5, 2014 at 20:06
  • 2
    No. Well, yes, you can do it, but they are not called decorators. Commented Apr 5, 2014 at 20:34
  • re closing this question, as someone learning Python I had been wondering about this too, and found the answers useful and concise. Commented Apr 5, 2014 at 23:00

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.