Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to quit the most outer function from an inner function?

Let's say I have code that looks like this:

def lab():
    letter = prompt() 
    def experiment_1():
        if letter == 1:
            print("check")
            #Would there be a way to quit the lab function right here?
    def experiment_2():
        if letter == 1:
            print("check2")

    experiment_1()
    experiment_2()
lab()

Would there be a way for me to quit the lab function right after I print "check"? I tried putting return at the end of experiment_1 but that just seems to go right to the next function which is experiment_2.

like image 861
Joshua Kim Avatar asked Dec 17 '16 15:12

Joshua Kim


People also ask

Is an inner function that has access to the variables of the outer function?

A closure is an inner function that has access to the outer (enclosing) function's variables — scope chain.

Can I define a function inside a function Python?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

How do you call a nested function in Python?

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.


1 Answers

The most obvious way is to raise an exception. It will allow you to get out from any depth. Define a custom exception and catch it at some outer level. For example:

class MyError(Exception):
    pass

def _lab():
    letter = prompt() 

    def experiment_1():
        if letter == 1:
            print("check")
            raise MyError

    def experiment_2():
        if letter == 1:
            print("check2")

    experiment_1()
    experiment_2()

def lab():
    try:
        return _lab()
    except MyError:
        return

lab()

This particular example is kind of ugly, but you should get the idea.

like image 123
warvariuc Avatar answered Oct 10 '22 21:10

warvariuc