0

I'm trying to be able call a function that is nested.

def function1():
    #code here
    def function2():
        return #variable
def function3():
    x = #the variable that is returned in function2
    # I'm not sure how to get it to equal the variable that was returned in function2

Thanks for the help!

2 Answers 2

2

You would have to return the function object; function2 is just another local variable inside function1 otherwise:

def function1():
    #code here
    def function2():
        return foo
    return function2

def function3():
    x = function1()()  # calls function2, returned by function1()

Calling function1() returns the function2 object, which is then called immediately.

Demo:

>>> def foo(bar):
...     def spam():
...         return bar + 42
...     return spam
... 
>>> foo(0)
<function spam at 0x10f371c08>
>>> foo(0)()
42
>>> def ham(eggs):
...     result = foo(eggs + 3)()
...     return result
... 
>>> ham(38)
83

Note how calling foo() returns a function object.

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

1 Comment

Thanks! The examples helped a lot!
1

To make that happen, you have to return function2 from function1 and then call function2 from function3 like this

def function1():
    #code here
    def function2():
        return #variable
    return function2

def function3():
    x = function1()
    print x()

Or, instead of storing function2 in x, you can simply do

def function3():
    print function1()()

6 Comments

I have two nested functions inside function 1. how do I only call one of them? function1()(function2)
@user3133761 Try and avoid nesting functions as much as possible.
I know. Sorry :/ I need the variable from inside the one function though and I'm not sure how to make that variable available outside the function. This is kinda my first larger program.
@user3133761 Then put all of them together in a class :) So, that all the functions can share the data
would I just be able to call them like regular variables then? I think I may have already tried that, but I probably didn't do it right. I'll try it again.
|

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.